From e65fc2fc02594a7c8640a6330b2373db1efb923e Mon Sep 17 00:00:00 2001 From: Michael Hwang Date: Thu, 22 Mar 2018 11:02:57 -0400 Subject: Add unit tests to reach 50% coverage Ripped out the dcae controller code which is no longer needed. Change-Id: I43906edb80bcd5e25445ec2a7175c6748b0ab2ae Signed-off-by: Michael Hwang Issue-ID: DCAEGEN2-257 --- docs/API.md | 10 +- pom.xml | 18 +- src/gen/java/io/swagger/api/DcaeServicesApi.java | 12 +- .../io/swagger/model/DCAEServiceComponent.java | 4 +- .../swagger/model/DCAEServiceComponentRequest.java | 4 +- .../factories/DcaeServicesApiServiceFactory.java | 10 +- .../api/impl/DcaeServicesApiServiceImpl.java | 26 +-- .../onap/dcae/inventory/InventoryApplication.java | 22 +- .../dcae/inventory/InventoryConfiguration.java | 59 +---- .../inventory/clients/DCAEControllerClient.java | 223 ------------------- .../exceptions/DCAEControllerClientException.java | 36 --- .../DCAEControllerConnectionException.java | 36 --- .../exceptions/DCAEControllerTimeoutException.java | 36 --- .../DCAEControllerConnectionExceptionMapper.java | 37 ---- .../mappers/DCAEControllerExceptionMapper.java | 41 ---- .../DCAEControllerTimeoutExceptionMapper.java | 37 ---- src/main/resources/config.json | 8 - src/main/resources/config.yml | 8 - .../java/DcaeServiceTypesApiServiceImplTests.java | 223 ------------------- src/test/java/DcaeServicesApiServiceImplTests.java | 243 --------------------- .../DcaeServicesGroupbyApiServiceImplTests.java | 88 -------- src/test/java/Util.java | 130 ----------- src/test/java/io/swagger/api/BootstrapTest.java | 43 ++++ src/test/java/io/swagger/api/Util.java | 130 +++++++++++ .../DcaeServiceTypesApiServiceFactoryTest.java | 37 ++++ .../DcaeServicesApiServiceFactoryTest.java | 37 ++++ .../DcaeServicesGroupbyApiServiceFactoryTest.java | 37 ++++ .../impl/DcaeServiceTypesApiServiceImplTests.java | 222 +++++++++++++++++++ .../impl/DcaeServicesApiServiceImplH2Tests.java | 132 +++++++++++ .../api/impl/DcaeServicesApiServiceImplTests.java | 236 ++++++++++++++++++++ .../DcaeServicesGroupbyApiServiceImplTests.java | 88 ++++++++ .../dcae/inventory/InventoryConfigurationTest.java | 61 ++++++ .../onap/dcae/inventory/LinkSerializerTest.java | 97 ++++++++ .../clients/DatabusControllerClientTest.java | 146 +++++++++++++ .../dcae/inventory/daos/DCAEServicesDAOTest.java | 84 +++++++ .../exception/mappers/DBIExceptionMapperTests.java | 117 ---------- .../DatabusControllerClientExceptionTest.java | 34 +++ .../mappers/DBIExceptionMapperTests.java | 117 ++++++++++ src/test/resources/config-databus.yaml | 4 + src/test/resources/config-inventory.yaml | 88 ++++++++ swagger_inventory.yaml | 19 +- version.properties | 4 +- 42 files changed, 1630 insertions(+), 1414 deletions(-) delete mode 100644 src/main/java/org/onap/dcae/inventory/clients/DCAEControllerClient.java delete mode 100644 src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerClientException.java delete mode 100644 src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerConnectionException.java delete mode 100644 src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerTimeoutException.java delete mode 100644 src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerConnectionExceptionMapper.java delete mode 100644 src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerExceptionMapper.java delete mode 100644 src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerTimeoutExceptionMapper.java delete mode 100644 src/test/java/DcaeServiceTypesApiServiceImplTests.java delete mode 100644 src/test/java/DcaeServicesApiServiceImplTests.java delete mode 100644 src/test/java/DcaeServicesGroupbyApiServiceImplTests.java delete mode 100644 src/test/java/Util.java create mode 100644 src/test/java/io/swagger/api/BootstrapTest.java create mode 100644 src/test/java/io/swagger/api/Util.java create mode 100644 src/test/java/io/swagger/api/factories/DcaeServiceTypesApiServiceFactoryTest.java create mode 100644 src/test/java/io/swagger/api/factories/DcaeServicesApiServiceFactoryTest.java create mode 100644 src/test/java/io/swagger/api/factories/DcaeServicesGroupbyApiServiceFactoryTest.java create mode 100644 src/test/java/io/swagger/api/impl/DcaeServiceTypesApiServiceImplTests.java create mode 100644 src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplH2Tests.java create mode 100644 src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplTests.java create mode 100644 src/test/java/io/swagger/api/impl/DcaeServicesGroupbyApiServiceImplTests.java create mode 100644 src/test/java/org/onap/dcae/inventory/InventoryConfigurationTest.java create mode 100644 src/test/java/org/onap/dcae/inventory/LinkSerializerTest.java create mode 100644 src/test/java/org/onap/dcae/inventory/clients/DatabusControllerClientTest.java create mode 100644 src/test/java/org/onap/dcae/inventory/daos/DCAEServicesDAOTest.java delete mode 100644 src/test/java/org/onap/dcae/inventory/exception/mappers/DBIExceptionMapperTests.java create mode 100644 src/test/java/org/onap/dcae/inventory/exceptions/DatabusControllerClientExceptionTest.java create mode 100644 src/test/java/org/onap/dcae/inventory/exceptions/mappers/DBIExceptionMapperTests.java create mode 100644 src/test/resources/config-databus.yaml create mode 100644 src/test/resources/config-inventory.yaml diff --git a/docs/API.md b/docs/API.md index a6f0472..ec0ff89 100644 --- a/docs/API.md +++ b/docs/API.md @@ -10,7 +10,7 @@ DCAE Inventory is a web service that provides the following: ### Version information -*Version* : 2.1.0 +*Version* : 3.0.0 ### Contact information @@ -189,8 +189,6 @@ Get a list of `DCAEService` objects. |HTTP Code|Description|Schema| |---|---|---| |**200**|List of `DCAEService` objects|[InlineResponse2001](#inlineresponse2001)| -|**502**|Bad response from DCAE controller|[ApiResponseMessage](#apiresponsemessage)| -|**504**|Failed to connect with DCAE controller|[ApiResponseMessage](#apiresponsemessage)| #### Consumes @@ -258,8 +256,6 @@ Get a `DCAEService` object. |---|---|---| |**200**|Single `DCAEService` object|[DCAEService](#dcaeservice)| |**404**|DCAE service not found|[ApiResponseMessage](#apiresponsemessage)| -|**502**|Bad response from DCAE controller|[ApiResponseMessage](#apiresponsemessage)| -|**504**|Failed to connect with DCAE controller|[ApiResponseMessage](#apiresponsemessage)| #### Consumes @@ -383,7 +379,7 @@ Remove an existing `DCAEService` object. |---|---|---| |**componentId**
*required*|The id format is unique to the source|string| |**componentLink**
*required*|Link to the underlying resource of this component|[Link](#link)| -|**componentSource**
*required*|Specifies the name of the underying source service that is responsible for this components|enum (DCAEController, DMaaPController)| +|**componentSource**
*required*|Specifies the name of the underying source service that is responsible for this components|enum (DMaaPController)| |**componentType**
*required*||string| |**created**
*required*||string(date-time)| |**location**
*optional*|Location information of the component|string| @@ -398,7 +394,7 @@ Remove an existing `DCAEService` object. |Name|Description|Schema| |---|---|---| |**componentId**
*required*|The id format is unique to the source|string| -|**componentSource**
*required*|Specifies the name of the underying source service that is responsible for this components|enum (DCAEController, DMaaPController)| +|**componentSource**
*required*|Specifies the name of the underying source service that is responsible for this components|enum (DMaaPController)| |**componentType**
*required*||string| |**shareable**
*required*|Used to determine if this component can be shared amongst different DCAE services|integer(int32)| diff --git a/pom.xml b/pom.xml index 7de89ba..0452a19 100644 --- a/pom.xml +++ b/pom.xml @@ -23,14 +23,14 @@ ECOMP is a trademark and service mark of AT&T Intellectual Property. org.onap.oparent oparent - 1.1.0-SNAPSHOT + 0.1.1 org.onap.dcaegen2.platform inventory-api - 1.3.0 + 3.0.0 dcaegen2-platform-inventory-api - + 1.1.1 @@ -190,6 +190,18 @@ ECOMP is a trademark and service mark of AT&T Intellectual Property. 1.6.5 test + + io.dropwizard + dropwizard-testing + ${dropwizard.version} + test + + + com.h2database + h2 + 1.4.197 + test + diff --git a/src/gen/java/io/swagger/api/DcaeServicesApi.java b/src/gen/java/io/swagger/api/DcaeServicesApi.java index 55d79f3..4c08cda 100644 --- a/src/gen/java/io/swagger/api/DcaeServicesApi.java +++ b/src/gen/java/io/swagger/api/DcaeServicesApi.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,9 +99,8 @@ public class DcaeServicesApi { @Produces({"application/json", "application/vnd.dcae.inventory.v1+json"}) @io.swagger.annotations.ApiOperation(value = "", notes = "Get a list of `DCAEService` objects.", response = InlineResponse2001.class, tags = {}) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "List of `DCAEService` objects", response = InlineResponse2001.class), - @io.swagger.annotations.ApiResponse(code = 502, message = "Bad response from DCAE controller", response = ApiResponseMessage.class), - @io.swagger.annotations.ApiResponse(code = 504, message = "Failed to connect with DCAE controller", response = ApiResponseMessage.class)}) + @io.swagger.annotations.ApiResponse(code = 200, message = "List of `DCAEService` objects", response = InlineResponse2001.class) + }) public Response dcaeServicesGet( @ApiParam(value = "DCAE service type name") @QueryParam("typeId") String typeId, @ApiParam(value = "") @QueryParam("vnfId") String vnfId, @@ -135,9 +134,8 @@ public class DcaeServicesApi { @io.swagger.annotations.ApiOperation(value = "", notes = "Get a `DCAEService` object.", response = DCAEService.class, tags = {}) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Single `DCAEService` object", response = DCAEService.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "DCAE service not found", response = ApiResponseMessage.class), - @io.swagger.annotations.ApiResponse(code = 502, message = "Bad response from DCAE controller", response = ApiResponseMessage.class), - @io.swagger.annotations.ApiResponse(code = 504, message = "Failed to connect with DCAE controller", response = ApiResponseMessage.class)}) + @io.swagger.annotations.ApiResponse(code = 404, message = "DCAE service not found", response = ApiResponseMessage.class) + }) public Response dcaeServicesServiceIdGet( @ApiParam(value = "", required = true) @PathParam("serviceId") String serviceId, @Context SecurityContext securityContext) diff --git a/src/gen/java/io/swagger/model/DCAEServiceComponent.java b/src/gen/java/io/swagger/model/DCAEServiceComponent.java index 6550c76..86d10ae 100644 --- a/src/gen/java/io/swagger/model/DCAEServiceComponent.java +++ b/src/gen/java/io/swagger/model/DCAEServiceComponent.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ public class DCAEServiceComponent { @ApiModelProperty(value = "Specifies the name of the underying source service that is responsible for this components", required = true, - allowableValues = "DCAEController, DMaaPController") + allowableValues = "DMaaPController") @JsonProperty("componentSource") public String getComponentSource() { return componentSource; diff --git a/src/gen/java/io/swagger/model/DCAEServiceComponentRequest.java b/src/gen/java/io/swagger/model/DCAEServiceComponentRequest.java index f65bf38..64d4127 100644 --- a/src/gen/java/io/swagger/model/DCAEServiceComponentRequest.java +++ b/src/gen/java/io/swagger/model/DCAEServiceComponentRequest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ public class DCAEServiceComponentRequest { @ApiModelProperty(value = "Specifies the name of the underying source service that is responsible for this components", required = true, - allowableValues = "DCAEController, DMaaPController") + allowableValues = "DMaaPController") @JsonProperty("componentSource") public String getComponentSource() { return componentSource; diff --git a/src/main/java/io/swagger/api/factories/DcaeServicesApiServiceFactory.java b/src/main/java/io/swagger/api/factories/DcaeServicesApiServiceFactory.java index 2fda7e7..ba27ada 100644 --- a/src/main/java/io/swagger/api/factories/DcaeServicesApiServiceFactory.java +++ b/src/main/java/io/swagger/api/factories/DcaeServicesApiServiceFactory.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ package io.swagger.api.factories; -import org.onap.dcae.inventory.clients.DCAEControllerClient; import org.onap.dcae.inventory.clients.DatabusControllerClient; import io.swagger.api.DcaeServicesApiService; import io.swagger.api.impl.DcaeServicesApiServiceImpl; @@ -29,23 +28,18 @@ import io.swagger.api.impl.DcaeServicesApiServiceImpl; public final class DcaeServicesApiServiceFactory { // Yes I agree this code is not great and I blame for Swagger for putting me in this spot. - private static DCAEControllerClient dcaeControllerClient; private static DatabusControllerClient databusControllerClient; //Utility classes, which are a collection of static members, are not meant to be instantiated. private DcaeServicesApiServiceFactory(){ } - public static void setDcaeControllerClient(DCAEControllerClient dcaeControllerClient) { - DcaeServicesApiServiceFactory.dcaeControllerClient = dcaeControllerClient; - } - public static void setDatabusControllerClient(DatabusControllerClient databusControllerClient) { DcaeServicesApiServiceFactory.databusControllerClient = databusControllerClient; } public static DcaeServicesApiService getDcaeServicesApi() { - return new DcaeServicesApiServiceImpl(dcaeControllerClient, databusControllerClient); + return new DcaeServicesApiServiceImpl(databusControllerClient); } } diff --git a/src/main/java/io/swagger/api/impl/DcaeServicesApiServiceImpl.java b/src/main/java/io/swagger/api/impl/DcaeServicesApiServiceImpl.java index f1219ac..26949af 100644 --- a/src/main/java/io/swagger/api/impl/DcaeServicesApiServiceImpl.java +++ b/src/main/java/io/swagger/api/impl/DcaeServicesApiServiceImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ package io.swagger.api.impl; -import org.onap.dcae.inventory.clients.DCAEControllerClient; import org.onap.dcae.inventory.clients.DatabusControllerClient; import org.onap.dcae.inventory.daos.DCAEServiceComponentsDAO; import org.onap.dcae.inventory.daos.DCAEServiceTransactionDAO; @@ -29,7 +28,6 @@ import org.onap.dcae.inventory.daos.InventoryDAOManager; import org.onap.dcae.inventory.dbthings.mappers.DCAEServiceObjectMapper; import org.onap.dcae.inventory.dbthings.models.DCAEServiceComponentObject; import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; -import org.onap.dcae.inventory.exceptions.DCAEControllerClientException; import org.onap.dcae.inventory.exceptions.DatabusControllerClientException; import io.swagger.api.*; import io.swagger.model.*; @@ -51,14 +49,11 @@ public class DcaeServicesApiServiceImpl extends DcaeServicesApiService { private static final Logger LOG = LoggerFactory.getLogger(DcaeServicesApiServiceImpl.class); private static final int PAGINATION_PAGE_SIZE = 25; - private static final String COMPONENT_SOURCE_DCAE_CONTROLLER = "DCAECONTROLLER"; private static final String COMPONENT_SOURCE_DATA_BUS_CONTROLLER = "DMAAPCONTROLLER"; - private final DCAEControllerClient dcaeControllerClient; private final DatabusControllerClient databusControllerClient; - public DcaeServicesApiServiceImpl(DCAEControllerClient dcaeControllerClient, DatabusControllerClient databusControllerClient) { - this.dcaeControllerClient = dcaeControllerClient; + public DcaeServicesApiServiceImpl(DatabusControllerClient databusControllerClient) { this.databusControllerClient = databusControllerClient; } @@ -90,22 +85,7 @@ public class DcaeServicesApiServiceImpl extends DcaeServicesApiService { // TODO: When putting together the components fail. Should this be a 500 case? // For now, this is just logged as a warning. - if (COMPONENT_SOURCE_DCAE_CONTROLLER.equalsIgnoreCase(sco.getComponentSource())) { - if (this.dcaeControllerClient != null) { - try { - DCAEControllerClient.ServiceInstance serviceInstance - = this.dcaeControllerClient.getServiceInstance(component.getComponentId()); - component.setStatus(serviceInstance.getStatus()); - // There's no specific location rather its inferred from the AIC tenant - component.setLocation(this.dcaeControllerClient.getLocation(serviceInstance)); - Link componentLink = Link.fromUri(this.dcaeControllerClient.constructResourceURI(sco.getComponentId())) - .rel("component").title(component.getComponentId()).build(); - component.setComponentLink(componentLink); - } catch (DCAEControllerClientException e) { - LOG.warn(String.format("%s, %s", e.getMessage(), sco.toString()), e); - } - } - } else if (COMPONENT_SOURCE_DATA_BUS_CONTROLLER.equalsIgnoreCase(sco.getComponentSource())) { + if (COMPONENT_SOURCE_DATA_BUS_CONTROLLER.equalsIgnoreCase(sco.getComponentSource())) { if (this.databusControllerClient != null) { try { if (this.databusControllerClient.isExists(sco.getComponentId())) { diff --git a/src/main/java/org/onap/dcae/inventory/InventoryApplication.java b/src/main/java/org/onap/dcae/inventory/InventoryApplication.java index 939cfdd..09ee260 100644 --- a/src/main/java/org/onap/dcae/inventory/InventoryApplication.java +++ b/src/main/java/org/onap/dcae/inventory/InventoryApplication.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +25,8 @@ import io.dropwizard.configuration.ConfigurationFactory; import io.dropwizard.configuration.ConfigurationFactoryFactory; import io.dropwizard.configuration.JsonConfigurationFactory; import io.dropwizard.configuration.UrlConfigurationSourceProvider; -import org.onap.dcae.inventory.clients.DCAEControllerClient; import org.onap.dcae.inventory.clients.DatabusControllerClient; import org.onap.dcae.inventory.exceptions.mappers.DBIExceptionMapper; -import org.onap.dcae.inventory.exceptions.mappers.DCAEControllerConnectionExceptionMapper; -import org.onap.dcae.inventory.exceptions.mappers.DCAEControllerTimeoutExceptionMapper; import org.onap.dcae.inventory.providers.NotFoundExceptionMapper; import org.onap.dcae.inventory.daos.InventoryDAOManager; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -144,21 +141,6 @@ public class InventoryApplication extends Application { simpleModule.addSerializer(Link.class, new LinkSerializer()); environment.getObjectMapper().registerModule(simpleModule); - // Setup DCAE controller client - // Used by the dcae-services API - if (configuration.getDcaeControllerConnection().getRequired()) { - final Client clientDCAEController = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration()) - .build("DCAEControllerClient"); - HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build(); - clientDCAEController.register(feature); - final DCAEControllerClient dcaeControllerClient = new DCAEControllerClient(clientDCAEController, configuration.getDcaeControllerConnection()); - DcaeServicesApiServiceFactory.setDcaeControllerClient(dcaeControllerClient); - - LOG.info("Use of DCAE controller client is required. Turned on."); - } else { - LOG.warn("Use of DCAE controller client is *not* required. Turned off."); - } - // Setup Databus controller client // Used by the dcae-services API if (configuration.getDatabusControllerConnection().getRequired()) { @@ -177,8 +159,6 @@ public class InventoryApplication extends Application { } environment.jersey().register(NotFoundExceptionMapper.class); - environment.jersey().register(DCAEControllerConnectionExceptionMapper.class); - environment.jersey().register(DCAEControllerTimeoutExceptionMapper.class); environment.jersey().register(DBIExceptionMapper.UnableToObtainConnectionExceptionMapper.class); environment.jersey().register(DBIExceptionMapper.UnableToExecuteStatementExceptionMapper.class); environment.jersey().register(DBIExceptionMapper.UnableToCreateStatementExceptionMapper.class); diff --git a/src/main/java/org/onap/dcae/inventory/InventoryConfiguration.java b/src/main/java/org/onap/dcae/inventory/InventoryConfiguration.java index 0dacb26..76a525a 100644 --- a/src/main/java/org/onap/dcae/inventory/InventoryConfiguration.java +++ b/src/main/java/org/onap/dcae/inventory/InventoryConfiguration.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * dcae-inventory * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,55 +34,6 @@ import javax.validation.constraints.NotNull; */ public class InventoryConfiguration extends Configuration { - public static class DCAEControllerConnectionConfiguration { - @NotEmpty - @JsonProperty - private String host; - - @NotNull - @JsonProperty - private Integer port; - - @NotEmpty - @JsonProperty - private String basePath; - - @NotEmpty - @JsonProperty - private String user; - - @NotEmpty - @JsonProperty - private String password; - - @JsonProperty - private Boolean required = true; - - public String getHost() { - return this.host; - } - - public Integer getPort() { - return this.port; - } - - public String getBasePath() { - return this.basePath; - } - - public String getUser() { - return this.user; - } - - public String getPassword() { - return this.password; - } - - public Boolean getRequired() { - return this.required; - } - } - public static class DatabusControllerConnectionConfiguration { @NotEmpty @JsonProperty @@ -132,10 +83,6 @@ public class InventoryConfiguration extends Configuration { @JsonProperty private DataSourceFactory database = new DataSourceFactory(); - @NotNull - @JsonProperty - private DCAEControllerConnectionConfiguration dcaeControllerConnection = new DCAEControllerConnectionConfiguration(); - @NotNull @JsonProperty private DatabusControllerConnectionConfiguration databusControllerConnection = new DatabusControllerConnectionConfiguration(); @@ -158,10 +105,6 @@ public class InventoryConfiguration extends Configuration { return this.database; } - public DCAEControllerConnectionConfiguration getDcaeControllerConnection() { - return this.dcaeControllerConnection; - } - public DatabusControllerConnectionConfiguration getDatabusControllerConnection() { return databusControllerConnection; } diff --git a/src/main/java/org/onap/dcae/inventory/clients/DCAEControllerClient.java b/src/main/java/org/onap/dcae/inventory/clients/DCAEControllerClient.java deleted file mode 100644 index b309cfd..0000000 --- a/src/main/java/org/onap/dcae/inventory/clients/DCAEControllerClient.java +++ /dev/null @@ -1,223 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.clients; - -import org.onap.dcae.inventory.InventoryConfiguration; -import org.onap.dcae.inventory.exceptions.DCAEControllerClientException; -import org.onap.dcae.inventory.exceptions.DCAEControllerConnectionException; -import org.onap.dcae.inventory.exceptions.DCAEControllerTimeoutException; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.ProcessingException; -import javax.ws.rs.client.Client; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; - -import static org.glassfish.jersey.client.authentication.HttpAuthenticationFeature.*; - -/** - * Created by mhwang on 5/12/16. - */ -public class DCAEControllerClient { - - /** - * Used for JSON objects of the form: - * "hostService": {"$ref": "/services/vm-docker-host-2/instances/mtl2"} - */ - public static class Reference { - - @JsonProperty("$ref") - private String ref; - - public String getRef() { - return ref; - } - - public void setRef(String ref) { - this.ref = ref; - } - - } - - /** - * Used for the JSON objects returned from /services/{service id}/instances/{instance id} - * calls. - */ - @JsonIgnoreProperties(ignoreUnknown = true) - public static class ServiceInstance { - - @JsonProperty("status") - private String status; - - /** - * Property points to the Docker host this Docker container runs on. - * This service instance is an application to be run as a Docker container if this value is not null. - */ - @JsonProperty("hostService") - @JsonInclude(JsonInclude.Include.NON_ABSENT) - private Reference hostService; - - /** - * Property points to the CDAP cluster this CDAP application is deployed on. - * This service instance is a CDAP application if this value is not null. - */ - @JsonProperty("clusterService") - @JsonInclude(JsonInclude.Include.NON_ABSENT) - private Reference clusterService; - - /** - * Property points to the location resource that this instance is associated with. - * This property is not null when the service instance is a "pure" VM. - */ - @JsonProperty("location") - @JsonInclude(JsonInclude.Include.NON_ABSENT) - private Reference location; - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public Reference getHostService() { - return hostService; - } - - public void setHostService(Reference hostService) { - this.hostService = hostService; - } - - public Reference getClusterService() { - return clusterService; - } - - public void setClusterService(Reference clusterService) { - this.clusterService = clusterService; - } - - public Reference getLocation() { - return location; - } - - public void setLocation(Reference location) { - this.location = location; - } - - } - - private static final Logger LOG = LoggerFactory.getLogger(DCAEControllerClient.class); - - private final Client client; - private final InventoryConfiguration.DCAEControllerConnectionConfiguration connectionConfiguration; - - public DCAEControllerClient(Client client, - InventoryConfiguration.DCAEControllerConnectionConfiguration connectionConfiguration) { - this.client = client; - this.connectionConfiguration = connectionConfiguration; - } - public URI constructResourceURI(String resourcePath) { - // TODO: Better way to construct this? - - // Make sure that the resource path has a "/" because the UriBuilder sucks and doesn't do it for us. - if (resourcePath.charAt(0) != '/') { - resourcePath = (new StringBuilder("/")).append(resourcePath).toString(); - } - - StringBuilder actualPath = new StringBuilder("/"); - actualPath.append(this.connectionConfiguration.getBasePath()); - actualPath.append(resourcePath); - - return UriBuilder.fromPath(actualPath.toString()).scheme("http").host(this.connectionConfiguration.getHost()) - .port(this.connectionConfiguration.getPort()).build(); - } - - public ServiceInstance getServiceInstance(String componentId) throws DCAEControllerClientException { - URI uri = constructResourceURI(componentId); - Response response = null; - - try { - response = client.target(uri).request(MediaType.APPLICATION_JSON_TYPE) - .header("Content-Type", "application/json") - .property(HTTP_AUTHENTICATION_BASIC_USERNAME, connectionConfiguration.getUser()) - .property(HTTP_AUTHENTICATION_BASIC_PASSWORD, connectionConfiguration.getPassword()).get(); - } catch (ProcessingException e) { - // Apparently the exceptions are wrapped which is not ideal because many different types of errors are embedded - // in single exception. TODO: May want to come back to split up the errors. - // Example: - // javax.ws.rs.ProcessingException: org.apache.http.conn.ConnectTimeoutException: Connect to :9998 - String message = "Connecting with DCAE controller probably timed out"; - LOG.error(message, e); - String exceptionMessage = String.format("%s: %s", message, e.getMessage()); - throw new DCAEControllerTimeoutException(exceptionMessage); - } catch (Exception e) { - String message = "Unexpected connection issue with DCAE controller"; - LOG.error(message, e); - String exceptionMessage = String.format("%s: %s", message, e.getMessage()); - throw new DCAEControllerConnectionException(exceptionMessage); - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Received response from DCAE controller: %d", response.getStatus())); - } - - if (response.getStatus() == 200) { - ObjectMapper om = new ObjectMapper(); - - try { - return om.readValue((InputStream) response.getEntity(), ServiceInstance.class); - } catch (IOException e) { - throw new DCAEControllerClientException(e); - } - } - - throw new DCAEControllerClientException(String.format("Unexpected error from DCAE controller: %d", response.getStatus())); - } - - public String getLocation(ServiceInstance serviceInstance) { - if (serviceInstance.getLocation() != null) { - return serviceInstance.getLocation().getRef(); - } else if (serviceInstance.getClusterService() != null) { - // Drill down: Location is on the underlying CDAP cluster service instance - String cdapClusterRef = serviceInstance.getClusterService().getRef(); - return getLocation(getServiceInstance(cdapClusterRef)); - } else if (serviceInstance.getHostService() != null) { - // Drill down: Location is on the underlying Docker host service instance - String dockerHostRef = serviceInstance.getHostService().getRef(); - return getLocation(getServiceInstance(dockerHostRef)); - } else { - throw new DCAEControllerClientException("No valid location for service instance"); - } - } - - - -} diff --git a/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerClientException.java b/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerClientException.java deleted file mode 100644 index b549ee1..0000000 --- a/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerClientException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exceptions; - -/** - * Created by mhwang on 5/13/16. - */ -public class DCAEControllerClientException extends RuntimeException { - - public DCAEControllerClientException(String message) { - super(message); - } - - public DCAEControllerClientException(Throwable e) { - super(e); - } - -} diff --git a/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerConnectionException.java b/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerConnectionException.java deleted file mode 100644 index f96ffbe..0000000 --- a/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerConnectionException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exceptions; - -/** - * Created by mhwang on 8/23/16. - */ -public class DCAEControllerConnectionException extends RuntimeException { - - public DCAEControllerConnectionException(String message) { - super(message); - } - - public DCAEControllerConnectionException(Throwable e) { - super(e); - } - -} diff --git a/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerTimeoutException.java b/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerTimeoutException.java deleted file mode 100644 index 48f5044..0000000 --- a/src/main/java/org/onap/dcae/inventory/exceptions/DCAEControllerTimeoutException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exceptions; - -/** - * Created by mhwang on 8/23/16. - */ -public class DCAEControllerTimeoutException extends RuntimeException { - - public DCAEControllerTimeoutException(String message) { - super(message); - } - - public DCAEControllerTimeoutException(Throwable e) { - super(e); - } - -} diff --git a/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerConnectionExceptionMapper.java b/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerConnectionExceptionMapper.java deleted file mode 100644 index e345c6e..0000000 --- a/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerConnectionExceptionMapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exceptions.mappers; - -import org.onap.dcae.inventory.exceptions.DCAEControllerConnectionException; - -import javax.ws.rs.core.Response; - -/** - * Created by mhwang on 8/23/16. - */ -public class DCAEControllerConnectionExceptionMapper extends DCAEControllerExceptionMapper { - - @Override - protected Response.Status getStatus() { - return Response.Status.BAD_GATEWAY; - } - -} diff --git a/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerExceptionMapper.java b/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerExceptionMapper.java deleted file mode 100644 index 8e4eb3b..0000000 --- a/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerExceptionMapper.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exceptions.mappers; - -import io.swagger.api.ApiResponseMessage; - -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - -/** - * Created by mhwang on 8/23/16. - */ -public abstract class DCAEControllerExceptionMapper implements ExceptionMapper { - - abstract protected Response.Status getStatus(); - - @Override - public Response toResponse(T e) { - ApiResponseMessage response = new ApiResponseMessage(ApiResponseMessage.ERROR, e.getMessage()); - return Response.status(this.getStatus()).entity(response).build(); - } - -} diff --git a/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerTimeoutExceptionMapper.java b/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerTimeoutExceptionMapper.java deleted file mode 100644 index 67eb6ca..0000000 --- a/src/main/java/org/onap/dcae/inventory/exceptions/mappers/DCAEControllerTimeoutExceptionMapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exceptions.mappers; - -import org.onap.dcae.inventory.exceptions.DCAEControllerTimeoutException; - -import javax.ws.rs.core.Response; - -/** - * Created by mhwang on 8/23/16. - */ -public class DCAEControllerTimeoutExceptionMapper extends DCAEControllerExceptionMapper { - - @Override - protected Response.Status getStatus() { - return Response.Status.GATEWAY_TIMEOUT; - } - -} diff --git a/src/main/resources/config.json b/src/main/resources/config.json index 436a181..89d887a 100644 --- a/src/main/resources/config.json +++ b/src/main/resources/config.json @@ -16,14 +16,6 @@ "evictionInterval": "10s", "minIdleTime": "1 minute" }, - "dcaeControllerConnection": { - "host": "dcae-controller-hostname", - "port": 9998, - "basePath": "resources", - "user": null, - "password": null, - "required": false - }, "databusControllerConnection": { "host": "databus-controller-hostname", "port": 8443, diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 505eea5..e882be0 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -40,14 +40,6 @@ database: # the minimum amount of time an connection must sit idle in the pool before it is eligible for eviction minIdleTime: 1 minute -dcaeControllerConnection: - host: dcae-controller-hostname - port: 9998 - # Apparently this is variable parameter amongst DCAE controller instances - basePath: resources - user: - password: - databusControllerConnection: host: databus-controller-hostname port: 8443 diff --git a/src/test/java/DcaeServiceTypesApiServiceImplTests.java b/src/test/java/DcaeServiceTypesApiServiceImplTests.java deleted file mode 100644 index 3882c53..0000000 --- a/src/test/java/DcaeServiceTypesApiServiceImplTests.java +++ /dev/null @@ -1,223 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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========================================================= - */ - -import org.onap.dcae.inventory.daos.DCAEServiceTypesDAO; -import org.onap.dcae.inventory.daos.DCAEServicesDAO; -import org.onap.dcae.inventory.daos.InventoryDAOManager; -import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; -import org.onap.dcae.inventory.dbthings.models.DCAEServiceTypeObject; -import io.swagger.api.impl.DcaeServiceTypesApiServiceImpl; -import io.swagger.model.DCAEServiceType; -import io.swagger.model.DCAEServiceTypeRequest; -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.Test; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriInfo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.*; - -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.Objects; -import java.util.UUID; - - -/** - * Created by mhwang on 10/27/16. - */ -@PrepareForTest({InventoryDAOManager.class}) -@RunWith(PowerMockRunner.class) -public class DcaeServiceTypesApiServiceImplTests { - - private final static Logger LOG = LoggerFactory.getLogger(DcaeServiceTypesApiServiceImplTests.class); - - private final static String URL_PATH = "http://testing-is-good.com"; - - private DcaeServiceTypesApiServiceImpl api = null; - private UriInfo uriInfo = null; - private DCAEServiceTypesDAO mockTypesDAO = null; - private DCAEServicesDAO mockServicesDAO = null; - - @Before - public void setupClass() { - api = new DcaeServiceTypesApiServiceImpl(); - - uriInfo = mock(UriInfo.class); - mockTypesDAO = mock(DCAEServiceTypesDAO.class); - mockServicesDAO = mock(DCAEServicesDAO.class); - - // PowerMockito does bytecode magic to mock static methods and use final classes - PowerMockito.mockStatic(InventoryDAOManager.class); - InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); - - when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); - when(mockDAOManager.getDCAEServiceTypesDAO()).thenReturn(mockTypesDAO); - when(mockDAOManager.getDCAEServicesDAO()).thenReturn(mockServicesDAO); - - when(uriInfo.getBaseUriBuilder()).thenReturn(UriBuilder.fromPath(URL_PATH)); - } - - private static boolean matchTypeVsTypeObject(DCAEServiceType serviceType, DCAEServiceTypeObject serviceTypeObject, String prefixPath) { - return Objects.equals(serviceType.getTypeId(), serviceTypeObject.getTypeId()) - && Objects.equals(serviceType.getTypeName(), serviceTypeObject.getTypeName()) - && Objects.equals(serviceType.getTypeVersion(), serviceTypeObject.getTypeVersion()) - && Objects.equals(serviceType.getOwner(), serviceTypeObject.getOwner()) - && Objects.equals(serviceType.getBlueprintTemplate(), serviceTypeObject.getBlueprintTemplate()) - && Objects.equals(serviceType.getCreated(), serviceTypeObject.getCreated().toDate()) - && Objects.equals(serviceType.getVnfTypes(), serviceTypeObject.getVnfTypes()) - && Objects.equals(serviceType.getServiceIds(), serviceTypeObject.getServiceIds()) - && Objects.equals(serviceType.getServiceLocations(), serviceTypeObject.getServiceLocations()) - && Objects.equals(serviceType.getAsdcResourceId(), serviceTypeObject.getAsdcResourceId()) - && Objects.equals(serviceType.getAsdcServiceId(), serviceTypeObject.getAsdcServiceId()) - && serviceType.getSelfLink().getUri().toString().contains(prefixPath) - && serviceType.getSelfLink().getUri().toString().contains(serviceTypeObject.getTypeId()); - } - - @Test - public void testGetSuccess() { - DCAEServiceTypeObject minimalFixture = new DCAEServiceTypeObject(); - minimalFixture.setTypeId("abc:1"); - minimalFixture.setTypeName("abc"); - minimalFixture.setTypeVersion(1); - minimalFixture.setOwner("tester"); - minimalFixture.setBlueprintTemplate("{ blueprint template goes here }"); - minimalFixture.setCreated(DateTime.parse("2016-10-28T00:00")); - - DCAEServiceTypeObject fullFixture = new DCAEServiceTypeObject(); - fullFixture.setTypeId("def:1"); - fullFixture.setTypeName("def"); - fullFixture.setTypeVersion(1); - fullFixture.setOwner("tester"); - fullFixture.setBlueprintTemplate("{ blueprint template goes here }"); - fullFixture.setCreated(DateTime.parse("2016-10-28T00:00")); - fullFixture.setAsdcServiceId("4bb4e740-3920-442d-9ed3-89f15bdbff8a"); - fullFixture.setAsdcResourceId("3ea9dfae-a00d-4da8-8c87-02a34de8fc02"); - fullFixture.setVnfTypes(Arrays.asList(new String[] { "vnf-marble", "vnf-granite" })); - fullFixture.setServiceIds(Arrays.asList(new String[] { "service-alpha", "service-bravo" })); - fullFixture.setServiceLocations(Arrays.asList(new String[] { "New York", "Washington" })); - - for (DCAEServiceTypeObject fixture : new DCAEServiceTypeObject[] {minimalFixture, fullFixture}) { - String someTypeId = fixture.getTypeId(); - when(mockTypesDAO.getByTypeId(someTypeId)).thenReturn(fixture); - - try { - Response response = api.dcaeServiceTypesTypeIdGet(someTypeId, uriInfo, null); - DCAEServiceType serviceType = (DCAEServiceType) response.getEntity(); - assertTrue("GET - 200 test case failed", matchTypeVsTypeObject(serviceType, fixture, URL_PATH)); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception: get 200", e); - } - } - } - - @Test - public void testGetNotFound() { - String someTypeId = "abc:1"; - when(mockTypesDAO.getByTypeId(someTypeId)).thenReturn(null); - - try { - Response response = api.dcaeServiceTypesTypeIdGet(someTypeId, uriInfo, null); - assertEquals("GET - 404 test case failed", 404, response.getStatus()); - } catch(Exception e) { - throw new RuntimeException("Unexpected exception: get 404", e); - } - } - - // TODO: Update this to check type id again. Must mock dao calls deeper. - private static boolean matchTypeVsTypeRequest(DCAEServiceType serviceType, DCAEServiceTypeRequest serviceTypeRequest, String prefixPath) { - return Objects.equals(serviceType.getTypeName(), serviceTypeRequest.getTypeName()) - && Objects.equals(serviceType.getTypeVersion(), serviceTypeRequest.getTypeVersion()) - && Objects.equals(serviceType.getOwner(), serviceTypeRequest.getOwner()) - && Objects.equals(serviceType.getBlueprintTemplate(), serviceTypeRequest.getBlueprintTemplate()) - && serviceType.getCreated() != null - && Objects.equals(serviceType.getVnfTypes(), serviceTypeRequest.getVnfTypes()) - && Objects.equals(serviceType.getServiceIds(), serviceTypeRequest.getServiceIds()) - && Objects.equals(serviceType.getServiceLocations(), serviceTypeRequest.getServiceLocations()) - && Objects.equals(serviceType.getAsdcResourceId(), serviceTypeRequest.getAsdcResourceId()) - && Objects.equals(serviceType.getAsdcServiceId(), serviceTypeRequest.getAsdcServiceId()) - && serviceType.getSelfLink().getUri().toString().contains(prefixPath); - } - - // TODO: Need to add tests for repeated POSTs == updates. - @Test - public void testPost() { - DCAEServiceTypeRequest minimalFixture = new DCAEServiceTypeRequest(); - minimalFixture.setTypeName("abc"); - minimalFixture.setTypeVersion(1); - minimalFixture.setOwner("tester"); - minimalFixture.setBlueprintTemplate("{ blueprint template goes here }"); - - DCAEServiceTypeRequest fullFixture = new DCAEServiceTypeRequest(); - fullFixture.setTypeName("def"); - fullFixture.setTypeVersion(1); - fullFixture.setOwner("tester"); - fullFixture.setBlueprintTemplate("{ blueprint template goes here }"); - fullFixture.setAsdcServiceId("4bb4e740-3920-442d-9ed3-89f15bdbff8a"); - fullFixture.setAsdcResourceId("3ea9dfae-a00d-4da8-8c87-02a34de8fc02"); - fullFixture.setVnfTypes(Arrays.asList(new String[] { "vnf-marble", "vnf-granite" })); - fullFixture.setServiceIds(Arrays.asList(new String[] { "service-alpha", "service-bravo" })); - fullFixture.setServiceLocations(Arrays.asList(new String[] { "New York", "Washington" })); - - for (DCAEServiceTypeRequest fixture : new DCAEServiceTypeRequest[] {minimalFixture, fullFixture}) { - try { - Response response = api.dcaeServiceTypesTypeIdPost(fixture, uriInfo, null); - DCAEServiceType serviceType = (DCAEServiceType) response.getEntity(); - assertTrue("POST - 200 test case failed", matchTypeVsTypeRequest(serviceType, fixture, URL_PATH)); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception: post new 200", e); - } - } - } - - @Test - public void testPostConflict() { - DCAEServiceTypeRequest minimalFixture = new DCAEServiceTypeRequest(); - minimalFixture.setTypeName("abc"); - minimalFixture.setTypeVersion(1); - minimalFixture.setOwner("tester"); - minimalFixture.setBlueprintTemplate("{ blueprint template goes here }"); - - UUID expectedTypeIdUUID = UUID.randomUUID(); - - DCAEServiceTypeObject fakeExistingType = new DCAEServiceTypeObject(); - fakeExistingType.setTypeId(expectedTypeIdUUID.toString()); - when(mockTypesDAO.getByRequestFromNotASDC(minimalFixture)).thenReturn(fakeExistingType); - when(mockServicesDAO.countByType(DCAEServiceObject.DCAEServiceStatus.RUNNING, fakeExistingType.getTypeId())).thenReturn(10); - - try { - Response response = api.dcaeServiceTypesTypeIdPost(minimalFixture, uriInfo, null); - assertEquals("POST - 401 test case failed", 409, response.getStatus()); - } catch (Exception e) { - throw new RuntimeException("Unexpected exception: post new 200", e); - } - } - -} diff --git a/src/test/java/DcaeServicesApiServiceImplTests.java b/src/test/java/DcaeServicesApiServiceImplTests.java deleted file mode 100644 index 75e3e00..0000000 --- a/src/test/java/DcaeServicesApiServiceImplTests.java +++ /dev/null @@ -1,243 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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========================================================= - */ - -import io.swagger.api.NotFoundException; -import io.swagger.api.impl.DcaeServicesApiServiceImpl; -import io.swagger.model.DCAEService; -import io.swagger.model.DCAEServiceRequest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.dcae.inventory.clients.DCAEControllerClient; -import org.onap.dcae.inventory.clients.DatabusControllerClient; -import org.onap.dcae.inventory.daos.DCAEServiceComponentsDAO; -import org.onap.dcae.inventory.daos.DCAEServiceTypesDAO; -import org.onap.dcae.inventory.daos.DCAEServicesDAO; -import org.onap.dcae.inventory.daos.InventoryDAOManager; -import org.onap.dcae.inventory.dbthings.models.DCAEServiceComponentObject; -import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static org.junit.Assert.fail; - -/** - * Created by mhwang on 9/25/17. - */ -@PrepareForTest({InventoryDAOManager.class}) -@RunWith(PowerMockRunner.class) -public class DcaeServicesApiServiceImplTests { - - private final static Logger LOG = LoggerFactory.getLogger(DcaeServicesApiServiceImplTests.class); - - private DCAEServiceTypesDAO mockTypesDAO = null; - private DCAEServicesDAO mockServicesDAO = null; - private DCAEServiceComponentsDAO mockComponentsDAO = null; - - @Before - public void setupClass() { - mockTypesDAO = mock(DCAEServiceTypesDAO.class); - mockServicesDAO = mock(DCAEServicesDAO.class); - mockComponentsDAO = mock(DCAEServiceComponentsDAO.class); - - // PowerMockito does bytecode magic to mock static methods and use final classes - PowerMockito.mockStatic(InventoryDAOManager.class); - InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); - - when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); - when(mockDAOManager.getDCAEServicesDAO()).thenReturn(mockServicesDAO); - when(mockDAOManager.getDCAEServiceComponentsDAO()).thenReturn(mockComponentsDAO); - when(mockDAOManager.getDCAEServiceTypesDAO()).thenReturn(mockTypesDAO); - } - - @Test - public void testCreateDCAEService() { - Method createDCAEService = null; - - // This block is a trick to make a private method accessible for testing - try { - createDCAEService = DcaeServicesApiServiceImpl.class.getDeclaredMethod("createDCAEService", DCAEServiceObject.class, - Collection.class, UriInfo.class); - createDCAEService.setAccessible(true); - } catch(NoSuchMethodException e) { - fail("Failed to do the reflection trick to test the private method: createDCAEService"); - } - - DCAEControllerClient dcc = mock(DCAEControllerClient.class); - DatabusControllerClient dbcc = mock(DatabusControllerClient.class); - DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dcc, dbcc); - - DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); - serviceRequest.setTypeId("type-id-abc"); - serviceRequest.setVnfId("vnf-id-def"); - String serviceId = "service-id-123"; - DCAEServiceObject serviceObject = new DCAEServiceObject(serviceId, serviceRequest); - List components = new ArrayList(); - UriInfo uriInfo = new Util.FakeUriInfo(); - - try { - DCAEService service = (DCAEService) createDCAEService.invoke(api, serviceObject, components, uriInfo); - assertEquals(service.getServiceId(), serviceObject.getServiceId()); - } catch(Exception e) { - fail("Failed to execute the hacked createDCAEService method"); - } - } - - @Test - public void testDcaeServicesServiceIdGet() { - String serviceId = "service-id-123"; - DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); - serviceRequest.setTypeId("type-id-abc"); - serviceRequest.setVnfId("vnf-id-def"); - DCAEServiceObject serviceObject = new DCAEServiceObject(serviceId, serviceRequest); - when(mockServicesDAO.getByServiceId(DCAEServiceObject.DCAEServiceStatus.RUNNING, serviceId)).thenReturn(serviceObject); - when(mockComponentsDAO.getByServiceId(serviceId)).thenReturn(new ArrayList()); - - DCAEControllerClient dcc = mock(DCAEControllerClient.class); - DatabusControllerClient dbcc = mock(DatabusControllerClient.class); - DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dcc, dbcc); - UriInfo uriInfo = new Util.FakeUriInfo(); - - try { - Response response = api.dcaeServicesServiceIdGet(serviceId, uriInfo, null); - assertEquals(response.getStatus(), 200); - } catch(NotFoundException e) { - fail("Service should have been found"); - } - } - - /* - Commented this unit test because could not get past Nullpointer in the line trying to mock the explicit "bind" function - call. Mockito does not handle mocking overloaded functions well so it goes into the actual method where an member variable - called foreman is null. - @Test - public void testDcaeServicesGet() { - Handle mockHandle = mock(Handle.class); - when(InventoryDAOManager.getInstance().getHandle()).thenReturn(mockHandle); - Query mockQueryGeneric = mock(Query.class); - Query mockQuery = mock(Query.class); - when(mockHandle.createQuery(any())).thenReturn(mockQueryGeneric); - when(mockQueryGeneric.map(any(DCAEServiceObjectMapper.class))).thenReturn(mockQuery); - // LOOK HERE! - doReturn(null).when(mockQuery.bind(anyString(), any(DateTime.class))); - when(mockQuery.bind(anyString(), anyInt())).thenReturn(null); - - DCAEControllerClient dcc = mock(DCAEControllerClient.class); - DatabusControllerClient dbcc = mock(DatabusControllerClient.class); - DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dcc, dbcc); - - String typeId = "some-type-id"; - String vnfId = "some-vnf-id"; - String vnfType = "some-vnf-type"; - String vnfLocation = "some-vnf-location"; - String componentType = "some-component-type"; - Boolean shareable = Boolean.TRUE; - DateTime created = null; - Integer offset = 0; - UriInfo uriInfo = new Util.FakeUriInfo(); - SecurityContext securityContext = null; - - when(mockQuery.list()).thenReturn(new ArrayList()); - - Response response = api.dcaeServicesGet(typeId, vnfId, vnfType, vnfLocation, componentType, shareable, created, - offset, uriInfo, securityContext); - assertEquals(response.getStatus(), 200); - } - */ - - @Test - public void testDcaeServicesServiceIdPutMissingType() { - String serviceId = "service-id-123"; - DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); - serviceRequest.setTypeId("type-id-abc"); - serviceRequest.setVnfId("vnf-id-def"); - - when(mockTypesDAO.getByTypeIdActiveOnly(serviceRequest.getTypeId())).thenReturn(null); - - DCAEControllerClient dcc = mock(DCAEControllerClient.class); - DatabusControllerClient dbcc = mock(DatabusControllerClient.class); - DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dcc, dbcc); - UriInfo uriInfo = new Util.FakeUriInfo(); - - Response response = api.dcaeServicesServiceIdPut(serviceId, serviceRequest, uriInfo, null); - assertEquals(response.getStatus(), 422); - } - - @Test - public void testDcaeServicesServiceIdDelete() { - String serviceId = "service-id-123"; - DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); - serviceRequest.setTypeId("type-id-abc"); - serviceRequest.setVnfId("vnf-id-def"); - DCAEServiceObject serviceObject = new DCAEServiceObject(serviceId, serviceRequest); - when(mockServicesDAO.getByServiceId(DCAEServiceObject.DCAEServiceStatus.RUNNING, serviceId)).thenReturn(serviceObject); - - DCAEControllerClient dcc = mock(DCAEControllerClient.class); - DatabusControllerClient dbcc = mock(DatabusControllerClient.class); - DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dcc, dbcc); - UriInfo uriInfo = new Util.FakeUriInfo(); - - try { - Response response = api.dcaeServicesServiceIdDelete(serviceId, null); - assertEquals(response.getStatus(), 200); - } catch(NotFoundException e) { - fail("Should have NOT thrown a NotFoundException"); - } catch(Exception e) { - LOG.error("Unexpected exception", e); - fail("Unexpected exception"); - } - } - - @Test - public void testDcaeServicesServiceIdDeleteMissingService() { - String serviceId = "service-id-123"; - when(mockServicesDAO.getByServiceId(DCAEServiceObject.DCAEServiceStatus.RUNNING, serviceId)).thenReturn(null); - - DCAEControllerClient dcc = mock(DCAEControllerClient.class); - DatabusControllerClient dbcc = mock(DatabusControllerClient.class); - DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dcc, dbcc); - UriInfo uriInfo = new Util.FakeUriInfo(); - - try { - api.dcaeServicesServiceIdDelete(serviceId, null); - fail("Should have thrown a NotFoundException"); - } catch(NotFoundException e) { - LOG.info("NotFoundException successfully thrown"); - } catch(Exception e) { - LOG.error("Unexpected exception", e); - fail("Unexpected exception"); - } - } - -} diff --git a/src/test/java/DcaeServicesGroupbyApiServiceImplTests.java b/src/test/java/DcaeServicesGroupbyApiServiceImplTests.java deleted file mode 100644 index 7ca8200..0000000 --- a/src/test/java/DcaeServicesGroupbyApiServiceImplTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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========================================================= - */ - -import io.swagger.api.impl.DcaeServicesGroupbyApiServiceImpl; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.dcae.inventory.daos.InventoryDAOManager; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Created by mhwang on 9/27/17. - */ -@PrepareForTest({InventoryDAOManager.class}) -@RunWith(PowerMockRunner.class) -public class DcaeServicesGroupbyApiServiceImplTests { - - @Before - public void setupClass() { - // PowerMockito does bytecode magic to mock static methods and use final classes - PowerMockito.mockStatic(InventoryDAOManager.class); - InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); - - when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); - } - - @Test - public void testBadRequest() { - DcaeServicesGroupbyApiServiceImpl api = new DcaeServicesGroupbyApiServiceImpl(); - - String propertyName = "non-existent"; - UriInfo uriInfo = new Util.FakeUriInfo(); - Response response = api.dcaeServicesGroupbyPropertyNameGet(propertyName, uriInfo, null); - assertEquals(response.getStatus(), 400); - } - - /* - Commented this unit test because could not get past Nullpointer in the line trying to mock the explicit "bind" function - call. Mockito does not handle mocking overloaded functions well so it goes into the actual method where an member variable - called foreman is null. - @Test - public void testNoResults() { - DcaeServicesGroupbyApiServiceImpl api = new DcaeServicesGroupbyApiServiceImpl(); - - String propertyName = "type"; - UriInfo uriInfo = new Util.FakeUriInfo(); - - Handle mockHandle = mock(Handle.class); - when(InventoryDAOManager.getInstance().getHandle()).thenReturn(mockHandle); - Query mockQueryGeneric = mock(Query.class); - when(mockHandle.createQuery(any())).thenReturn(mockQueryGeneric); - // LOOK HERE! - when(mockQueryGeneric.bind(any(), DCAEServiceObject.DCAEServiceStatus.RUNNING)).thenReturn(mockQueryGeneric); - when(mockQueryGeneric.list()).thenReturn(null); - - Response response = api.dcaeServicesGroupbyPropertyNameGet(propertyName, uriInfo, null); - assertEquals(response.getStatus(), 400); - } - */ - -} diff --git a/src/test/java/Util.java b/src/test/java/Util.java deleted file mode 100644 index 9607148..0000000 --- a/src/test/java/Util.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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========================================================= - */ - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.PathSegment; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriInfo; -import java.net.URI; -import java.util.List; - -/** - * Created by mhwang on 9/25/17. - */ -public class Util { - - public static class FakeUriInfo implements UriInfo { - - @Override - public String getPath() { - return null; - } - - @Override - public String getPath(boolean b) { - return null; - } - - @Override - public List getPathSegments() { - return null; - } - - @Override - public List getPathSegments(boolean b) { - return null; - } - - @Override - public URI getRequestUri() { - return null; - } - - @Override - public UriBuilder getRequestUriBuilder() { - return null; - } - - @Override - public URI getAbsolutePath() { - return null; - } - - @Override - public UriBuilder getAbsolutePathBuilder() { - return null; - } - - @Override - public URI getBaseUri() { - return null; - } - - @Override - public UriBuilder getBaseUriBuilder() { - return UriBuilder.fromUri("http://some-fake-base-uri"); - } - - @Override - public MultivaluedMap getPathParameters() { - return null; - } - - @Override - public MultivaluedMap getPathParameters(boolean b) { - return null; - } - - @Override - public MultivaluedMap getQueryParameters() { - return null; - } - - @Override - public MultivaluedMap getQueryParameters(boolean b) { - return null; - } - - @Override - public List getMatchedURIs() { - return null; - } - - @Override - public List getMatchedURIs(boolean b) { - return null; - } - - @Override - public List getMatchedResources() { - return null; - } - - @Override - public URI resolve(URI uri) { - return null; - } - - @Override - public URI relativize(URI uri) { - return null; - } - } -} diff --git a/src/test/java/io/swagger/api/BootstrapTest.java b/src/test/java/io/swagger/api/BootstrapTest.java new file mode 100644 index 0000000..7c86d8c --- /dev/null +++ b/src/test/java/io/swagger/api/BootstrapTest.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package io.swagger.api; + +import org.junit.Test; + +import javax.servlet.ServletException; + +import static org.junit.Assert.fail; + +/** + * Created by mhwang on 3/22/18. + */ +public class BootstrapTest { + + @Test + public void testNoServletConfig() { + try { + (new Bootstrap()).init(null); + } catch(ServletException e) { + fail("This might be a valid failure. Should investigate."); + } + } + +} diff --git a/src/test/java/io/swagger/api/Util.java b/src/test/java/io/swagger/api/Util.java new file mode 100644 index 0000000..8f9e09f --- /dev/null +++ b/src/test/java/io/swagger/api/Util.java @@ -0,0 +1,130 @@ +package io.swagger.api;/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.PathSegment; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import java.net.URI; +import java.util.List; + +/** + * Created by mhwang on 9/25/17. + */ +public class Util { + + public static class FakeUriInfo implements UriInfo { + + @Override + public String getPath() { + return null; + } + + @Override + public String getPath(boolean b) { + return null; + } + + @Override + public List getPathSegments() { + return null; + } + + @Override + public List getPathSegments(boolean b) { + return null; + } + + @Override + public URI getRequestUri() { + return null; + } + + @Override + public UriBuilder getRequestUriBuilder() { + return null; + } + + @Override + public URI getAbsolutePath() { + return null; + } + + @Override + public UriBuilder getAbsolutePathBuilder() { + return null; + } + + @Override + public URI getBaseUri() { + return null; + } + + @Override + public UriBuilder getBaseUriBuilder() { + return UriBuilder.fromUri("http://some-fake-base-uri"); + } + + @Override + public MultivaluedMap getPathParameters() { + return null; + } + + @Override + public MultivaluedMap getPathParameters(boolean b) { + return null; + } + + @Override + public MultivaluedMap getQueryParameters() { + return null; + } + + @Override + public MultivaluedMap getQueryParameters(boolean b) { + return null; + } + + @Override + public List getMatchedURIs() { + return null; + } + + @Override + public List getMatchedURIs(boolean b) { + return null; + } + + @Override + public List getMatchedResources() { + return null; + } + + @Override + public URI resolve(URI uri) { + return null; + } + + @Override + public URI relativize(URI uri) { + return null; + } + } +} diff --git a/src/test/java/io/swagger/api/factories/DcaeServiceTypesApiServiceFactoryTest.java b/src/test/java/io/swagger/api/factories/DcaeServiceTypesApiServiceFactoryTest.java new file mode 100644 index 0000000..6b385df --- /dev/null +++ b/src/test/java/io/swagger/api/factories/DcaeServiceTypesApiServiceFactoryTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package io.swagger.api.factories; + +import org.junit.Test; + +import static junit.framework.TestCase.assertNotNull; + +/** + * Created by mhwang on 3/22/18. + */ +public class DcaeServiceTypesApiServiceFactoryTest { + + @Test + public void testGetDcaeServiceTypesApi() { + assertNotNull(DcaeServiceTypesApiServiceFactory.getDcaeServiceTypesApi()); + } + +} diff --git a/src/test/java/io/swagger/api/factories/DcaeServicesApiServiceFactoryTest.java b/src/test/java/io/swagger/api/factories/DcaeServicesApiServiceFactoryTest.java new file mode 100644 index 0000000..d9c6808 --- /dev/null +++ b/src/test/java/io/swagger/api/factories/DcaeServicesApiServiceFactoryTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package io.swagger.api.factories; + +import org.junit.Test; + +import static junit.framework.TestCase.assertNotNull; + +/** + * Created by mhwang on 3/22/18. + */ +public class DcaeServicesApiServiceFactoryTest { + + @Test + public void testGetDcaeServicesApi() { + assertNotNull(DcaeServicesApiServiceFactory.getDcaeServicesApi()); + } + +} diff --git a/src/test/java/io/swagger/api/factories/DcaeServicesGroupbyApiServiceFactoryTest.java b/src/test/java/io/swagger/api/factories/DcaeServicesGroupbyApiServiceFactoryTest.java new file mode 100644 index 0000000..033c8a6 --- /dev/null +++ b/src/test/java/io/swagger/api/factories/DcaeServicesGroupbyApiServiceFactoryTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package io.swagger.api.factories; + +import org.junit.Test; + +import static junit.framework.TestCase.assertNotNull; + +/** + * Created by mhwang on 3/22/18. + */ +public class DcaeServicesGroupbyApiServiceFactoryTest { + + @Test + public void testGetDcaeServicesGroupbyApi() { + assertNotNull(DcaeServicesGroupbyApiServiceFactory.getDcaeServicesGroupbyApi()); + } + +} diff --git a/src/test/java/io/swagger/api/impl/DcaeServiceTypesApiServiceImplTests.java b/src/test/java/io/swagger/api/impl/DcaeServiceTypesApiServiceImplTests.java new file mode 100644 index 0000000..4a47787 --- /dev/null +++ b/src/test/java/io/swagger/api/impl/DcaeServiceTypesApiServiceImplTests.java @@ -0,0 +1,222 @@ +package io.swagger.api.impl;/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import org.onap.dcae.inventory.daos.DCAEServiceTypesDAO; +import org.onap.dcae.inventory.daos.DCAEServicesDAO; +import org.onap.dcae.inventory.daos.InventoryDAOManager; +import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; +import org.onap.dcae.inventory.dbthings.models.DCAEServiceTypeObject; +import io.swagger.model.DCAEServiceType; +import io.swagger.model.DCAEServiceTypeRequest; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; + +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + + +/** + * Created by mhwang on 10/27/16. + */ +@PrepareForTest({InventoryDAOManager.class}) +@RunWith(PowerMockRunner.class) +public class DcaeServiceTypesApiServiceImplTests { + + private final static Logger LOG = LoggerFactory.getLogger(DcaeServiceTypesApiServiceImplTests.class); + + private final static String URL_PATH = "http://testing-is-good.com"; + + private DcaeServiceTypesApiServiceImpl api = null; + private UriInfo uriInfo = null; + private DCAEServiceTypesDAO mockTypesDAO = null; + private DCAEServicesDAO mockServicesDAO = null; + + @Before + public void setupClass() { + api = new DcaeServiceTypesApiServiceImpl(); + + uriInfo = mock(UriInfo.class); + mockTypesDAO = mock(DCAEServiceTypesDAO.class); + mockServicesDAO = mock(DCAEServicesDAO.class); + + // PowerMockito does bytecode magic to mock static methods and use final classes + PowerMockito.mockStatic(InventoryDAOManager.class); + InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); + + when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); + when(mockDAOManager.getDCAEServiceTypesDAO()).thenReturn(mockTypesDAO); + when(mockDAOManager.getDCAEServicesDAO()).thenReturn(mockServicesDAO); + + when(uriInfo.getBaseUriBuilder()).thenReturn(UriBuilder.fromPath(URL_PATH)); + } + + private static boolean matchTypeVsTypeObject(DCAEServiceType serviceType, DCAEServiceTypeObject serviceTypeObject, String prefixPath) { + return Objects.equals(serviceType.getTypeId(), serviceTypeObject.getTypeId()) + && Objects.equals(serviceType.getTypeName(), serviceTypeObject.getTypeName()) + && Objects.equals(serviceType.getTypeVersion(), serviceTypeObject.getTypeVersion()) + && Objects.equals(serviceType.getOwner(), serviceTypeObject.getOwner()) + && Objects.equals(serviceType.getBlueprintTemplate(), serviceTypeObject.getBlueprintTemplate()) + && Objects.equals(serviceType.getCreated(), serviceTypeObject.getCreated().toDate()) + && Objects.equals(serviceType.getVnfTypes(), serviceTypeObject.getVnfTypes()) + && Objects.equals(serviceType.getServiceIds(), serviceTypeObject.getServiceIds()) + && Objects.equals(serviceType.getServiceLocations(), serviceTypeObject.getServiceLocations()) + && Objects.equals(serviceType.getAsdcResourceId(), serviceTypeObject.getAsdcResourceId()) + && Objects.equals(serviceType.getAsdcServiceId(), serviceTypeObject.getAsdcServiceId()) + && serviceType.getSelfLink().getUri().toString().contains(prefixPath) + && serviceType.getSelfLink().getUri().toString().contains(serviceTypeObject.getTypeId()); + } + + @Test + public void testGetSuccess() { + DCAEServiceTypeObject minimalFixture = new DCAEServiceTypeObject(); + minimalFixture.setTypeId("abc:1"); + minimalFixture.setTypeName("abc"); + minimalFixture.setTypeVersion(1); + minimalFixture.setOwner("tester"); + minimalFixture.setBlueprintTemplate("{ blueprint template goes here }"); + minimalFixture.setCreated(DateTime.parse("2016-10-28T00:00")); + + DCAEServiceTypeObject fullFixture = new DCAEServiceTypeObject(); + fullFixture.setTypeId("def:1"); + fullFixture.setTypeName("def"); + fullFixture.setTypeVersion(1); + fullFixture.setOwner("tester"); + fullFixture.setBlueprintTemplate("{ blueprint template goes here }"); + fullFixture.setCreated(DateTime.parse("2016-10-28T00:00")); + fullFixture.setAsdcServiceId("4bb4e740-3920-442d-9ed3-89f15bdbff8a"); + fullFixture.setAsdcResourceId("3ea9dfae-a00d-4da8-8c87-02a34de8fc02"); + fullFixture.setVnfTypes(Arrays.asList(new String[] { "vnf-marble", "vnf-granite" })); + fullFixture.setServiceIds(Arrays.asList(new String[] { "service-alpha", "service-bravo" })); + fullFixture.setServiceLocations(Arrays.asList(new String[] { "New York", "Washington" })); + + for (DCAEServiceTypeObject fixture : new DCAEServiceTypeObject[] {minimalFixture, fullFixture}) { + String someTypeId = fixture.getTypeId(); + when(mockTypesDAO.getByTypeId(someTypeId)).thenReturn(fixture); + + try { + Response response = api.dcaeServiceTypesTypeIdGet(someTypeId, uriInfo, null); + DCAEServiceType serviceType = (DCAEServiceType) response.getEntity(); + assertTrue("GET - 200 test case failed", matchTypeVsTypeObject(serviceType, fixture, URL_PATH)); + } catch (Exception e) { + throw new RuntimeException("Unexpected exception: get 200", e); + } + } + } + + @Test + public void testGetNotFound() { + String someTypeId = "abc:1"; + when(mockTypesDAO.getByTypeId(someTypeId)).thenReturn(null); + + try { + Response response = api.dcaeServiceTypesTypeIdGet(someTypeId, uriInfo, null); + assertEquals("GET - 404 test case failed", 404, response.getStatus()); + } catch(Exception e) { + throw new RuntimeException("Unexpected exception: get 404", e); + } + } + + // TODO: Update this to check type id again. Must mock dao calls deeper. + private static boolean matchTypeVsTypeRequest(DCAEServiceType serviceType, DCAEServiceTypeRequest serviceTypeRequest, String prefixPath) { + return Objects.equals(serviceType.getTypeName(), serviceTypeRequest.getTypeName()) + && Objects.equals(serviceType.getTypeVersion(), serviceTypeRequest.getTypeVersion()) + && Objects.equals(serviceType.getOwner(), serviceTypeRequest.getOwner()) + && Objects.equals(serviceType.getBlueprintTemplate(), serviceTypeRequest.getBlueprintTemplate()) + && serviceType.getCreated() != null + && Objects.equals(serviceType.getVnfTypes(), serviceTypeRequest.getVnfTypes()) + && Objects.equals(serviceType.getServiceIds(), serviceTypeRequest.getServiceIds()) + && Objects.equals(serviceType.getServiceLocations(), serviceTypeRequest.getServiceLocations()) + && Objects.equals(serviceType.getAsdcResourceId(), serviceTypeRequest.getAsdcResourceId()) + && Objects.equals(serviceType.getAsdcServiceId(), serviceTypeRequest.getAsdcServiceId()) + && serviceType.getSelfLink().getUri().toString().contains(prefixPath); + } + + // TODO: Need to add tests for repeated POSTs == updates. + @Test + public void testPost() { + DCAEServiceTypeRequest minimalFixture = new DCAEServiceTypeRequest(); + minimalFixture.setTypeName("abc"); + minimalFixture.setTypeVersion(1); + minimalFixture.setOwner("tester"); + minimalFixture.setBlueprintTemplate("{ blueprint template goes here }"); + + DCAEServiceTypeRequest fullFixture = new DCAEServiceTypeRequest(); + fullFixture.setTypeName("def"); + fullFixture.setTypeVersion(1); + fullFixture.setOwner("tester"); + fullFixture.setBlueprintTemplate("{ blueprint template goes here }"); + fullFixture.setAsdcServiceId("4bb4e740-3920-442d-9ed3-89f15bdbff8a"); + fullFixture.setAsdcResourceId("3ea9dfae-a00d-4da8-8c87-02a34de8fc02"); + fullFixture.setVnfTypes(Arrays.asList(new String[] { "vnf-marble", "vnf-granite" })); + fullFixture.setServiceIds(Arrays.asList(new String[] { "service-alpha", "service-bravo" })); + fullFixture.setServiceLocations(Arrays.asList(new String[] { "New York", "Washington" })); + + for (DCAEServiceTypeRequest fixture : new DCAEServiceTypeRequest[] {minimalFixture, fullFixture}) { + try { + Response response = api.dcaeServiceTypesTypeIdPost(fixture, uriInfo, null); + DCAEServiceType serviceType = (DCAEServiceType) response.getEntity(); + assertTrue("POST - 200 test case failed", matchTypeVsTypeRequest(serviceType, fixture, URL_PATH)); + } catch (Exception e) { + throw new RuntimeException("Unexpected exception: post new 200", e); + } + } + } + + @Test + public void testPostConflict() { + DCAEServiceTypeRequest minimalFixture = new DCAEServiceTypeRequest(); + minimalFixture.setTypeName("abc"); + minimalFixture.setTypeVersion(1); + minimalFixture.setOwner("tester"); + minimalFixture.setBlueprintTemplate("{ blueprint template goes here }"); + + UUID expectedTypeIdUUID = UUID.randomUUID(); + + DCAEServiceTypeObject fakeExistingType = new DCAEServiceTypeObject(); + fakeExistingType.setTypeId(expectedTypeIdUUID.toString()); + when(mockTypesDAO.getByRequestFromNotASDC(minimalFixture)).thenReturn(fakeExistingType); + when(mockServicesDAO.countByType(DCAEServiceObject.DCAEServiceStatus.RUNNING, fakeExistingType.getTypeId())).thenReturn(10); + + try { + Response response = api.dcaeServiceTypesTypeIdPost(minimalFixture, uriInfo, null); + assertEquals("POST - 401 test case failed", 409, response.getStatus()); + } catch (Exception e) { + throw new RuntimeException("Unexpected exception: post new 200", e); + } + } + +} diff --git a/src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplH2Tests.java b/src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplH2Tests.java new file mode 100644 index 0000000..0a3b777 --- /dev/null +++ b/src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplH2Tests.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package io.swagger.api.impl; + +import com.codahale.metrics.MetricRegistry; +import io.dropwizard.db.DataSourceFactory; +import io.dropwizard.jackson.Jackson; +import io.dropwizard.jdbi.DBIFactory; +import io.dropwizard.setup.Environment; +import io.swagger.api.Util; +import io.swagger.model.DCAEServiceRequest; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.dcae.inventory.clients.DatabusControllerClient; +import org.onap.dcae.inventory.daos.*; +import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.skife.jdbi.v2.DBI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.core.UriInfo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Created by mhwang on 9/25/17. + * + * This test covers the gap in DcaeServicesApiServiceImplTests - testing the GET query interface + * The approach taken here is standing up an H2 in-memory database which is different from the + * original test which made an attempt to mock the database calls but ran into an impasse. The + * test here was not included in the original class because of conflicting setup operations. + */ +@PrepareForTest({InventoryDAOManager.class}) +@RunWith(PowerMockRunner.class) +public class DcaeServicesApiServiceImplH2Tests { + + private final static Logger LOG = LoggerFactory.getLogger(DcaeServicesApiServiceImplH2Tests.class); + + private DCAEServicesDAO mockServicesDAO = null; + private DCAEServiceComponentsDAO mockComponentsDAO = null; + private DCAEServicesComponentsMapsDAO mockComponentsMapsDAO = null; + + // https://stackoverflow.com/questions/35825383/how-to-test-jdbi-daos-with-h2-in-memory-database + // Caused by: java.lang.ClassNotFoundException: Unable to load class: org.h2.Driver from ClassLoader:sun.misc.Launcher$AppClassLoader@18b4aac2;ClassLoader:sun.misc.Launcher$AppClassLoader@18b4aac2 + protected DataSourceFactory getDataSourceFactory() + { + DataSourceFactory dataSourceFactory = new DataSourceFactory(); + dataSourceFactory.setDriverClass( "org.h2.Driver" ); + dataSourceFactory.setUrl( "jdbc:h2:mem:testDb" ); + dataSourceFactory.setUser( "sa" ); + dataSourceFactory.setPassword( "sa" ); + + return dataSourceFactory; + } + + @Before + public void setUp() { + Environment env = new Environment( "test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null ); + DBI dbi = new DBIFactory().build( env, getDataSourceFactory(), "test" ); + mockServicesDAO = dbi.onDemand(DCAEServicesDAO.class); + mockComponentsDAO = dbi.onDemand(DCAEServiceComponentsDAO.class); + mockComponentsMapsDAO = dbi.onDemand(DCAEServicesComponentsMapsDAO.class); + + // PowerMockito does bytecode magic to mock static methods and use final classes + PowerMockito.mockStatic(InventoryDAOManager.class); + InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); + + when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); + when(mockDAOManager.getHandle()).thenReturn(dbi.open()); + } + + @Test + public void testDcaeServicesGet () { + mockServicesDAO.createTable(); + mockComponentsDAO.createTable(); + mockComponentsMapsDAO.createTable(); + + DCAEServiceRequest request = new DCAEServiceRequest(); + request.setTypeId("some-type-id"); + request.setVnfId("some-vnf-id"); + request.setVnfType("some-vnf-type"); + request.setVnfLocation("some-vnf-location"); + request.setDeploymentRef("some-deployment-ref"); + DCAEServiceObject so = new DCAEServiceObject("some-service-id", request); + mockServicesDAO.insert(so); + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + String typeId = "some-type-id"; + String vnfId = "some-vnf-id"; + String vnfType = "some-vnf-type"; + String vnfLocation = "some-vnf-location"; + String componentType = "some-component-type"; + Boolean shareable = Boolean.TRUE; + DateTime created = null; + Integer offset = 0; + UriInfo uriInfo = new Util.FakeUriInfo(); + SecurityContext securityContext = null; + Response response = api.dcaeServicesGet(typeId, vnfId, vnfType, vnfLocation, componentType, shareable, created, + offset, uriInfo, securityContext); + assertEquals(response.getStatus(), 200); + } + +} diff --git a/src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplTests.java b/src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplTests.java new file mode 100644 index 0000000..64b7f88 --- /dev/null +++ b/src/test/java/io/swagger/api/impl/DcaeServicesApiServiceImplTests.java @@ -0,0 +1,236 @@ +package io.swagger.api.impl;/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import io.swagger.api.NotFoundException; +import io.swagger.api.Util; +import io.swagger.model.DCAEService; +import io.swagger.model.DCAEServiceRequest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.dcae.inventory.clients.DatabusControllerClient; +import org.onap.dcae.inventory.daos.DCAEServiceComponentsDAO; +import org.onap.dcae.inventory.daos.DCAEServiceTypesDAO; +import org.onap.dcae.inventory.daos.DCAEServicesDAO; +import org.onap.dcae.inventory.daos.InventoryDAOManager; +import org.onap.dcae.inventory.dbthings.models.DCAEServiceComponentObject; +import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.junit.Assert.fail; + +/** + * Created by mhwang on 9/25/17. + */ +@PrepareForTest({InventoryDAOManager.class}) +@RunWith(PowerMockRunner.class) +public class DcaeServicesApiServiceImplTests { + + private final static Logger LOG = LoggerFactory.getLogger(DcaeServicesApiServiceImplTests.class); + + private DCAEServiceTypesDAO mockTypesDAO = null; + private DCAEServicesDAO mockServicesDAO = null; + private DCAEServiceComponentsDAO mockComponentsDAO = null; + + @Before + public void setupClass() { + mockTypesDAO = mock(DCAEServiceTypesDAO.class); + mockServicesDAO = mock(DCAEServicesDAO.class); + mockComponentsDAO = mock(DCAEServiceComponentsDAO.class); + + // PowerMockito does bytecode magic to mock static methods and use final classes + PowerMockito.mockStatic(InventoryDAOManager.class); + InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); + + when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); + when(mockDAOManager.getDCAEServicesDAO()).thenReturn(mockServicesDAO); + when(mockDAOManager.getDCAEServiceComponentsDAO()).thenReturn(mockComponentsDAO); + when(mockDAOManager.getDCAEServiceTypesDAO()).thenReturn(mockTypesDAO); + } + + @Test + public void testCreateDCAEService() { + Method createDCAEService = null; + + // This block is a trick to make a private method accessible for testing + try { + createDCAEService = DcaeServicesApiServiceImpl.class.getDeclaredMethod("createDCAEService", DCAEServiceObject.class, + Collection.class, UriInfo.class); + createDCAEService.setAccessible(true); + } catch(NoSuchMethodException e) { + fail("Failed to do the reflection trick to test the private method: createDCAEService"); + } + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + + DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); + serviceRequest.setTypeId("type-id-abc"); + serviceRequest.setVnfId("vnf-id-def"); + String serviceId = "service-id-123"; + DCAEServiceObject serviceObject = new DCAEServiceObject(serviceId, serviceRequest); + List components = new ArrayList(); + UriInfo uriInfo = new Util.FakeUriInfo(); + + try { + DCAEService service = (DCAEService) createDCAEService.invoke(api, serviceObject, components, uriInfo); + assertEquals(service.getServiceId(), serviceObject.getServiceId()); + } catch(Exception e) { + fail("Failed to execute the hacked createDCAEService method"); + } + } + + @Test + public void testDcaeServicesServiceIdGet() { + String serviceId = "service-id-123"; + DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); + serviceRequest.setTypeId("type-id-abc"); + serviceRequest.setVnfId("vnf-id-def"); + DCAEServiceObject serviceObject = new DCAEServiceObject(serviceId, serviceRequest); + when(mockServicesDAO.getByServiceId(DCAEServiceObject.DCAEServiceStatus.RUNNING, serviceId)).thenReturn(serviceObject); + when(mockComponentsDAO.getByServiceId(serviceId)).thenReturn(new ArrayList()); + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + UriInfo uriInfo = new Util.FakeUriInfo(); + + try { + Response response = api.dcaeServicesServiceIdGet(serviceId, uriInfo, null); + assertEquals(response.getStatus(), 200); + } catch(NotFoundException e) { + fail("Service should have been found"); + } + } + + /* + Commented this unit test because could not get past Nullpointer in the line trying to mock the explicit "bind" function + call. Mockito does not handle mocking overloaded functions well so it goes into the actual method where an member variable + called foreman is null. + @Test + public void testDcaeServicesGet() { + Handle mockHandle = mock(Handle.class); + when(InventoryDAOManager.getInstance().getHandle()).thenReturn(mockHandle); + Query mockQueryGeneric = mock(Query.class); + Query mockQuery = mock(Query.class); + when(mockHandle.createQuery(any())).thenReturn(mockQueryGeneric); + when(mockQueryGeneric.map(any(DCAEServiceObjectMapper.class))).thenReturn(mockQuery); + // LOOK HERE! + doReturn(null).when(mockQuery.bind(anyString(), any(DateTime.class))); + when(mockQuery.bind(anyString(), anyInt())).thenReturn(null); + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + + String typeId = "some-type-id"; + String vnfId = "some-vnf-id"; + String vnfType = "some-vnf-type"; + String vnfLocation = "some-vnf-location"; + String componentType = "some-component-type"; + Boolean shareable = Boolean.TRUE; + DateTime created = null; + Integer offset = 0; + UriInfo uriInfo = new io.swagger.api.Util.FakeUriInfo(); + SecurityContext securityContext = null; + + when(mockQuery.list()).thenReturn(new ArrayList()); + + Response response = api.dcaeServicesGet(typeId, vnfId, vnfType, vnfLocation, componentType, shareable, created, + offset, uriInfo, securityContext); + assertEquals(response.getStatus(), 200); + } + */ + + @Test + public void testDcaeServicesServiceIdPutMissingType() { + String serviceId = "service-id-123"; + DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); + serviceRequest.setTypeId("type-id-abc"); + serviceRequest.setVnfId("vnf-id-def"); + + when(mockTypesDAO.getByTypeIdActiveOnly(serviceRequest.getTypeId())).thenReturn(null); + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + UriInfo uriInfo = new Util.FakeUriInfo(); + + Response response = api.dcaeServicesServiceIdPut(serviceId, serviceRequest, uriInfo, null); + assertEquals(response.getStatus(), 422); + } + + @Test + public void testDcaeServicesServiceIdDelete() { + String serviceId = "service-id-123"; + DCAEServiceRequest serviceRequest = new DCAEServiceRequest(); + serviceRequest.setTypeId("type-id-abc"); + serviceRequest.setVnfId("vnf-id-def"); + DCAEServiceObject serviceObject = new DCAEServiceObject(serviceId, serviceRequest); + when(mockServicesDAO.getByServiceId(DCAEServiceObject.DCAEServiceStatus.RUNNING, serviceId)).thenReturn(serviceObject); + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + UriInfo uriInfo = new Util.FakeUriInfo(); + + try { + Response response = api.dcaeServicesServiceIdDelete(serviceId, null); + assertEquals(response.getStatus(), 200); + } catch(NotFoundException e) { + fail("Should have NOT thrown a NotFoundException"); + } catch(Exception e) { + LOG.error("Unexpected exception", e); + fail("Unexpected exception"); + } + } + + @Test + public void testDcaeServicesServiceIdDeleteMissingService() { + String serviceId = "service-id-123"; + when(mockServicesDAO.getByServiceId(DCAEServiceObject.DCAEServiceStatus.RUNNING, serviceId)).thenReturn(null); + + DatabusControllerClient dbcc = mock(DatabusControllerClient.class); + DcaeServicesApiServiceImpl api = new DcaeServicesApiServiceImpl(dbcc); + UriInfo uriInfo = new Util.FakeUriInfo(); + + try { + api.dcaeServicesServiceIdDelete(serviceId, null); + fail("Should have thrown a NotFoundException"); + } catch(NotFoundException e) { + LOG.info("NotFoundException successfully thrown"); + } catch(Exception e) { + LOG.error("Unexpected exception", e); + fail("Unexpected exception"); + } + } + +} diff --git a/src/test/java/io/swagger/api/impl/DcaeServicesGroupbyApiServiceImplTests.java b/src/test/java/io/swagger/api/impl/DcaeServicesGroupbyApiServiceImplTests.java new file mode 100644 index 0000000..0ae2c3a --- /dev/null +++ b/src/test/java/io/swagger/api/impl/DcaeServicesGroupbyApiServiceImplTests.java @@ -0,0 +1,88 @@ +package io.swagger.api.impl;/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import io.swagger.api.Util; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.dcae.inventory.daos.InventoryDAOManager; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Created by mhwang on 9/27/17. + */ +@PrepareForTest({InventoryDAOManager.class}) +@RunWith(PowerMockRunner.class) +public class DcaeServicesGroupbyApiServiceImplTests { + + @Before + public void setupClass() { + // PowerMockito does bytecode magic to mock static methods and use final classes + PowerMockito.mockStatic(InventoryDAOManager.class); + InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); + + when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); + } + + @Test + public void testBadRequest() { + DcaeServicesGroupbyApiServiceImpl api = new DcaeServicesGroupbyApiServiceImpl(); + + String propertyName = "non-existent"; + UriInfo uriInfo = new Util.FakeUriInfo(); + Response response = api.dcaeServicesGroupbyPropertyNameGet(propertyName, uriInfo, null); + assertEquals(response.getStatus(), 400); + } + + /* + Commented this unit test because could not get past Nullpointer in the line trying to mock the explicit "bind" function + call. Mockito does not handle mocking overloaded functions well so it goes into the actual method where an member variable + called foreman is null. + @Test + public void testNoResults() { + DcaeServicesGroupbyApiServiceImpl api = new DcaeServicesGroupbyApiServiceImpl(); + + String propertyName = "type"; + UriInfo uriInfo = new io.swagger.api.Util.FakeUriInfo(); + + Handle mockHandle = mock(Handle.class); + when(InventoryDAOManager.getInstance().getHandle()).thenReturn(mockHandle); + Query mockQueryGeneric = mock(Query.class); + when(mockHandle.createQuery(any())).thenReturn(mockQueryGeneric); + // LOOK HERE! + when(mockQueryGeneric.bind(any(), DCAEServiceObject.DCAEServiceStatus.RUNNING)).thenReturn(mockQueryGeneric); + when(mockQueryGeneric.list()).thenReturn(null); + + Response response = api.dcaeServicesGroupbyPropertyNameGet(propertyName, uriInfo, null); + assertEquals(response.getStatus(), 400); + } + */ + +} diff --git a/src/test/java/org/onap/dcae/inventory/InventoryConfigurationTest.java b/src/test/java/org/onap/dcae/inventory/InventoryConfigurationTest.java new file mode 100644 index 0000000..f9dadb8 --- /dev/null +++ b/src/test/java/org/onap/dcae/inventory/InventoryConfigurationTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcae.inventory; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.dropwizard.configuration.YamlConfigurationFactory; +import io.dropwizard.jackson.Jackson; +import io.dropwizard.jersey.validation.Validators; +import org.junit.Test; + +import javax.validation.Validator; +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Created by mhwang on 3/22/18. + */ +public class InventoryConfigurationTest { + + final private ObjectMapper objectMapper = Jackson.newObjectMapper(); + final private Validator validator = Validators.newValidator(); + final private YamlConfigurationFactory factory + = new YamlConfigurationFactory<>(InventoryConfiguration.class, validator, objectMapper, "dw"); + + @Test + public void testInventoryConfigurationLoad() { + try { + final File yaml = new File(Thread.currentThread().getContextClassLoader().getResource("config-inventory.yaml").getPath()); + InventoryConfiguration configuration = factory.build(yaml); + + assertEquals(configuration.getDatabusControllerConnection().getHost(), "databus-controller-hostname"); + assertEquals((long) configuration.getDatabusControllerConnection().getPort(), 8443); + assertEquals(configuration.getDatabusControllerConnection().getRequired(), true); + + assertEquals(configuration.getDataSourceFactory().getUrl(), "jdbc:postgresql://127.0.0.1:5432/dcae_inv"); + } catch(Exception e) { + fail("Failed to load config-inventory"); + } + } + +} diff --git a/src/test/java/org/onap/dcae/inventory/LinkSerializerTest.java b/src/test/java/org/onap/dcae/inventory/LinkSerializerTest.java new file mode 100644 index 0000000..81b0554 --- /dev/null +++ b/src/test/java/org/onap/dcae/inventory/LinkSerializerTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcae.inventory; + +import com.fasterxml.jackson.core.JsonGenerator; +import org.junit.Test; + +import javax.ws.rs.core.Link; +import javax.ws.rs.core.UriBuilder; + +import java.net.URI; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; + +/** + * Created by mhwang on 3/25/18. + */ +public class LinkSerializerTest { + + @Test + public void testSerialize() { + JsonGenerator jg = mock(JsonGenerator.class); + + try { + Link link = new Link() { + @Override + public URI getUri() { + try { + return new URI("http://localhost/some-title"); + } catch (Exception e) { + return null; + } + } + + @Override + public UriBuilder getUriBuilder() { + return null; + } + + @Override + public String getRel() { + return "self"; + } + + @Override + public List getRels() { + return null; + } + + @Override + public String getTitle() { + return "some-title"; + } + + @Override + public String getType() { + return null; + } + + @Override + public Map getParams() { + return null; + } + + @Override + public String toString() { + return null; + } + }; + (new LinkSerializer()).serialize(link, jg, null); + } catch (Exception e) { + fail("Failed to serialze link"); + } + } + +} diff --git a/src/test/java/org/onap/dcae/inventory/clients/DatabusControllerClientTest.java b/src/test/java/org/onap/dcae/inventory/clients/DatabusControllerClientTest.java new file mode 100644 index 0000000..ae2f2ff --- /dev/null +++ b/src/test/java/org/onap/dcae/inventory/clients/DatabusControllerClientTest.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcae.inventory.clients; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.dropwizard.configuration.ConfigurationException; +import io.dropwizard.configuration.YamlConfigurationFactory; +import io.dropwizard.jackson.Jackson; +import io.dropwizard.jersey.validation.Validators; +import org.junit.Before; +import org.junit.Test; +import org.onap.dcae.inventory.InventoryConfiguration; +import org.onap.dcae.inventory.exceptions.DatabusControllerClientException; + +import javax.validation.Validator; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; + +/** + * Created by mhwang on 3/22/18. + */ +public class DatabusControllerClientTest { + + final private ObjectMapper objectMapper = Jackson.newObjectMapper(); + final private Validator validator = Validators.newValidator(); + final private YamlConfigurationFactory factory + = new YamlConfigurationFactory<>(InventoryConfiguration.DatabusControllerConnectionConfiguration.class, validator, objectMapper, "dw"); + + private InventoryConfiguration.DatabusControllerConnectionConfiguration configuration = null; + + @Before + public void setupClass() throws IOException, ConfigurationException { + final File yaml = new File(Thread.currentThread().getContextClassLoader().getResource("config-databus.yaml").getPath()); + this.configuration = factory.build(yaml); + } + + @Test + public void testConstructResourceURI() { + DatabusControllerClient client = new DatabusControllerClient(null, this.configuration); + URI uri = client.constructResourceURI("/some-path"); + assertEquals(uri.toString(), "https://databus-controller-hostname:8443/some-path"); + } + + private DatabusControllerClient setupForIsExists(Response mockResponse) { + Client mockClient = mock(Client.class); + WebTarget mockWebTarget = mock(WebTarget.class); + Invocation.Builder mockBuilder = mock(Invocation.Builder.class); + + try { + URI uri = new URI("https://databus-controller-hostname:8443/some-component-id"); + when(mockClient.target(uri)).thenReturn(mockWebTarget); + //when(mockClient.target(new URI(any()))).thenReturn(mockWebTarget); + } catch(URISyntaxException e) { + fail("URI syntax error"); + } + + when(mockWebTarget.request(MediaType.APPLICATION_JSON_TYPE)).thenReturn(mockBuilder); + when(mockBuilder.header(any(), any())).thenReturn(mockBuilder); + + when(mockBuilder.get()).thenReturn(mockResponse); + return new DatabusControllerClient(mockClient, this.configuration); + + } + + @Test + public void testIsExists() { + Response mockResponse = mock(Response.class); + when(mockResponse.getStatus()).thenReturn(200); + InputStream stream = new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8)); + when(mockResponse.getEntity()).thenReturn(stream); + + DatabusControllerClient client = setupForIsExists(mockResponse); + + try { + assertEquals(client.isExists("some-component-id"), false); + } catch(Exception e) { + fail("Unexpected exception"); + } + } + + private void testIsExistsErrors(int statusError) { + Response mockResponse = mock(Response.class); + when(mockResponse.getStatus()).thenReturn(statusError); + + DatabusControllerClient client = setupForIsExists(mockResponse); + + try { + client.isExists("some-component-id"); + fail("This was supposed to be a fail case. Exception not thrown."); + } catch(DatabusControllerClientException e) { + // Expected exception + } catch(Exception e) { + fail("Unexpected exception"); + } + } + + @Test + public void testIsExists401() { + testIsExistsErrors(401); + } + + @Test + public void testIsExists403() { + testIsExistsErrors(403); + } + + @Test + public void testIsExists500() { + testIsExistsErrors(500); + } + +} diff --git a/src/test/java/org/onap/dcae/inventory/daos/DCAEServicesDAOTest.java b/src/test/java/org/onap/dcae/inventory/daos/DCAEServicesDAOTest.java new file mode 100644 index 0000000..af05704 --- /dev/null +++ b/src/test/java/org/onap/dcae/inventory/daos/DCAEServicesDAOTest.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcae.inventory.daos; + +import com.codahale.metrics.MetricRegistry; +import io.dropwizard.db.DataSourceFactory; +import io.dropwizard.jackson.Jackson; +import io.dropwizard.jdbi.DBIFactory; +import io.dropwizard.setup.Environment; +import io.swagger.model.DCAEServiceRequest; +import org.junit.Before; +import org.junit.Test; +import org.onap.dcae.inventory.dbthings.models.DCAEServiceObject; +import org.skife.jdbi.v2.DBI; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * Created by mhwang on 3/25/18. + */ +public class DCAEServicesDAOTest { + + private DCAEServicesDAO fooDAO; + + // Learned about the H2 approach from here: + // https://stackoverflow.com/questions/35825383/how-to-test-jdbi-daos-with-h2-in-memory-database + protected DataSourceFactory getDataSourceFactory() + { + DataSourceFactory dataSourceFactory = new DataSourceFactory(); + dataSourceFactory.setDriverClass( "org.h2.Driver" ); + dataSourceFactory.setUrl( "jdbc:h2:mem:testDb" ); + dataSourceFactory.setUser( "sa" ); + dataSourceFactory.setPassword( "sa" ); + + return dataSourceFactory; + } + + @Before + public void setUp() { + Environment env = new Environment( "test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null ); + DBI dbi = new DBIFactory().build( env, getDataSourceFactory(), "test" ); + fooDAO = dbi.onDemand(DCAEServicesDAO.class); + } + + @Test + public void testSaveAndGet() { + try { + fooDAO.createTable(); + DCAEServiceRequest request = new DCAEServiceRequest(); + request.setTypeId("some-type-id"); + request.setVnfId("some-vnf-id"); + request.setVnfType("some-vnf-type"); + request.setVnfLocation("some-vnf-location"); + request.setDeploymentRef("some-deployment-ref"); + DCAEServiceObject so = new DCAEServiceObject("some-service-id", request); + fooDAO.insert(so); + + DCAEServiceObject target = fooDAO.getByServiceId("some-service-id"); + assertEquals(target.getServiceId(), so.getServiceId()); + } catch(Exception e) { + fail("Failure at some point in this compound test."); + } + } +} diff --git a/src/test/java/org/onap/dcae/inventory/exception/mappers/DBIExceptionMapperTests.java b/src/test/java/org/onap/dcae/inventory/exception/mappers/DBIExceptionMapperTests.java deleted file mode 100644 index 7c04295..0000000 --- a/src/test/java/org/onap/dcae/inventory/exception/mappers/DBIExceptionMapperTests.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * dcae-inventory - * ================================================================================ - * Copyright (C) 2017 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.dcae.inventory.exception.mappers; - -import org.onap.dcae.inventory.daos.InventoryDAOManager; -import org.onap.dcae.inventory.exceptions.mappers.DBIExceptionMapper; -import io.swagger.api.ApiResponseMessage; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; -import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; -import org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException; - -import javax.ws.rs.core.Response; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Created by mhwang on 3/8/17. - */ -@PrepareForTest({InventoryDAOManager.class}) -@RunWith(PowerMockRunner.class) -public class DBIExceptionMapperTests { - - @Test - public void testReinitializeSuccess() { - // PowerMockito does bytecode magic to mock static methods and use final classes - PowerMockito.mockStatic(InventoryDAOManager.class); - InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); - when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); - - RuntimeException fakeException = new RuntimeException("Spoofing database failure"); - - // Test UnableToObtainConnectionExceptionMapper - - DBIExceptionMapper.UnableToObtainConnectionExceptionMapper mapperOne = new DBIExceptionMapper.UnableToObtainConnectionExceptionMapper(); - Response responseOne = mapperOne.toResponse(new UnableToObtainConnectionException(fakeException)); - assert responseOne.getStatus() == 502; - String messageOne = ((ApiResponseMessage) responseOne.getEntity()).getMessage(); - assert messageOne.contains("successfully reset"); - - // Test UnableToCreateStatementExceptionMapper - - DBIExceptionMapper.UnableToCreateStatementExceptionMapper mapperTwo = new DBIExceptionMapper.UnableToCreateStatementExceptionMapper(); - Response responseTwo = mapperTwo.toResponse(new UnableToCreateStatementException(fakeException)); - assert responseTwo.getStatus() == 502; - String messageTwo = ((ApiResponseMessage) responseTwo.getEntity()).getMessage(); - assert messageTwo.contains("successfully reset"); - - // Test UnableToExecuteStatementExceptionMapper - - DBIExceptionMapper.UnableToExecuteStatementExceptionMapper mapperThree = new DBIExceptionMapper.UnableToExecuteStatementExceptionMapper(); - Response responseThree = mapperThree.toResponse(new UnableToExecuteStatementException(fakeException)); - assert responseThree.getStatus() == 502; - String messageThree = ((ApiResponseMessage) responseThree.getEntity()).getMessage(); - assert messageThree.contains("successfully reset"); - } - - @Test - public void testReinitializeFailed() { - // PowerMockito does bytecode magic to mock static methods and use final classes - PowerMockito.mockStatic(InventoryDAOManager.class); - InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); - when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); - Mockito.doThrow(new RuntimeException("Spoof initialization failure")).when(mockDAOManager).initialize(); - - RuntimeException fakeException = new RuntimeException("Spoofing database failure"); - - // Test UnableToObtainConnectionExceptionMapper - - DBIExceptionMapper.UnableToObtainConnectionExceptionMapper mapperOne = new DBIExceptionMapper.UnableToObtainConnectionExceptionMapper(); - Response responseOne = mapperOne.toResponse(new UnableToObtainConnectionException(fakeException)); - assert responseOne.getStatus() == 502; - String messageOne = ((ApiResponseMessage) responseOne.getEntity()).getMessage(); - assert !messageOne.contains("successfully reset"); - - // Test UnableToCreateStatementExceptionMapper - - DBIExceptionMapper.UnableToCreateStatementExceptionMapper mapperTwo = new DBIExceptionMapper.UnableToCreateStatementExceptionMapper(); - Response responseTwo = mapperTwo.toResponse(new UnableToCreateStatementException(fakeException)); - assert responseTwo.getStatus() == 502; - String messageTwo = ((ApiResponseMessage) responseTwo.getEntity()).getMessage(); - assert !messageTwo.contains("successfully reset"); - - // Test UnableToExecuteStatementExceptionMapper - - DBIExceptionMapper.UnableToExecuteStatementExceptionMapper mapperThree = new DBIExceptionMapper.UnableToExecuteStatementExceptionMapper(); - Response responseThree = mapperThree.toResponse(new UnableToExecuteStatementException(fakeException)); - assert responseThree.getStatus() == 502; - String messageThree = ((ApiResponseMessage) responseThree.getEntity()).getMessage(); - assert !messageThree.contains("successfully reset"); - } - -} diff --git a/src/test/java/org/onap/dcae/inventory/exceptions/DatabusControllerClientExceptionTest.java b/src/test/java/org/onap/dcae/inventory/exceptions/DatabusControllerClientExceptionTest.java new file mode 100644 index 0000000..fcde16e --- /dev/null +++ b/src/test/java/org/onap/dcae/inventory/exceptions/DatabusControllerClientExceptionTest.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcae.inventory.exceptions; + +import org.junit.Test; + +/** + * Created by mhwang on 3/26/18. + */ +public class DatabusControllerClientExceptionTest { + + @Test + public void testBasicConstructor() { + new DatabusControllerClientException(new RuntimeException("Boo")); + } +} diff --git a/src/test/java/org/onap/dcae/inventory/exceptions/mappers/DBIExceptionMapperTests.java b/src/test/java/org/onap/dcae/inventory/exceptions/mappers/DBIExceptionMapperTests.java new file mode 100644 index 0000000..b0d5ba4 --- /dev/null +++ b/src/test/java/org/onap/dcae/inventory/exceptions/mappers/DBIExceptionMapperTests.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * dcae-inventory + * ================================================================================ + * Copyright (C) 2017 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.dcae.inventory.exceptions.mappers; + +import org.onap.dcae.inventory.daos.InventoryDAOManager; +import org.onap.dcae.inventory.exceptions.mappers.DBIExceptionMapper; +import io.swagger.api.ApiResponseMessage; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; +import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; +import org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException; + +import javax.ws.rs.core.Response; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Created by mhwang on 3/8/17. + */ +@PrepareForTest({InventoryDAOManager.class}) +@RunWith(PowerMockRunner.class) +public class DBIExceptionMapperTests { + + @Test + public void testReinitializeSuccess() { + // PowerMockito does bytecode magic to mock static methods and use final classes + PowerMockito.mockStatic(InventoryDAOManager.class); + InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); + when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); + + RuntimeException fakeException = new RuntimeException("Spoofing database failure"); + + // Test UnableToObtainConnectionExceptionMapper + + DBIExceptionMapper.UnableToObtainConnectionExceptionMapper mapperOne = new DBIExceptionMapper.UnableToObtainConnectionExceptionMapper(); + Response responseOne = mapperOne.toResponse(new UnableToObtainConnectionException(fakeException)); + assert responseOne.getStatus() == 502; + String messageOne = ((ApiResponseMessage) responseOne.getEntity()).getMessage(); + assert messageOne.contains("successfully reset"); + + // Test UnableToCreateStatementExceptionMapper + + DBIExceptionMapper.UnableToCreateStatementExceptionMapper mapperTwo = new DBIExceptionMapper.UnableToCreateStatementExceptionMapper(); + Response responseTwo = mapperTwo.toResponse(new UnableToCreateStatementException(fakeException)); + assert responseTwo.getStatus() == 502; + String messageTwo = ((ApiResponseMessage) responseTwo.getEntity()).getMessage(); + assert messageTwo.contains("successfully reset"); + + // Test UnableToExecuteStatementExceptionMapper + + DBIExceptionMapper.UnableToExecuteStatementExceptionMapper mapperThree = new DBIExceptionMapper.UnableToExecuteStatementExceptionMapper(); + Response responseThree = mapperThree.toResponse(new UnableToExecuteStatementException(fakeException)); + assert responseThree.getStatus() == 502; + String messageThree = ((ApiResponseMessage) responseThree.getEntity()).getMessage(); + assert messageThree.contains("successfully reset"); + } + + @Test + public void testReinitializeFailed() { + // PowerMockito does bytecode magic to mock static methods and use final classes + PowerMockito.mockStatic(InventoryDAOManager.class); + InventoryDAOManager mockDAOManager = mock(InventoryDAOManager.class); + when(InventoryDAOManager.getInstance()).thenReturn(mockDAOManager); + Mockito.doThrow(new RuntimeException("Spoof initialization failure")).when(mockDAOManager).initialize(); + + RuntimeException fakeException = new RuntimeException("Spoofing database failure"); + + // Test UnableToObtainConnectionExceptionMapper + + DBIExceptionMapper.UnableToObtainConnectionExceptionMapper mapperOne = new DBIExceptionMapper.UnableToObtainConnectionExceptionMapper(); + Response responseOne = mapperOne.toResponse(new UnableToObtainConnectionException(fakeException)); + assert responseOne.getStatus() == 502; + String messageOne = ((ApiResponseMessage) responseOne.getEntity()).getMessage(); + assert !messageOne.contains("successfully reset"); + + // Test UnableToCreateStatementExceptionMapper + + DBIExceptionMapper.UnableToCreateStatementExceptionMapper mapperTwo = new DBIExceptionMapper.UnableToCreateStatementExceptionMapper(); + Response responseTwo = mapperTwo.toResponse(new UnableToCreateStatementException(fakeException)); + assert responseTwo.getStatus() == 502; + String messageTwo = ((ApiResponseMessage) responseTwo.getEntity()).getMessage(); + assert !messageTwo.contains("successfully reset"); + + // Test UnableToExecuteStatementExceptionMapper + + DBIExceptionMapper.UnableToExecuteStatementExceptionMapper mapperThree = new DBIExceptionMapper.UnableToExecuteStatementExceptionMapper(); + Response responseThree = mapperThree.toResponse(new UnableToExecuteStatementException(fakeException)); + assert responseThree.getStatus() == 502; + String messageThree = ((ApiResponseMessage) responseThree.getEntity()).getMessage(); + assert !messageThree.contains("successfully reset"); + } + +} diff --git a/src/test/resources/config-databus.yaml b/src/test/resources/config-databus.yaml new file mode 100644 index 0000000..f51c869 --- /dev/null +++ b/src/test/resources/config-databus.yaml @@ -0,0 +1,4 @@ +host: databus-controller-hostname +port: 8443 +mechId: some-mech-id +password: some-mech-password diff --git a/src/test/resources/config-inventory.yaml b/src/test/resources/config-inventory.yaml new file mode 100644 index 0000000..3206566 --- /dev/null +++ b/src/test/resources/config-inventory.yaml @@ -0,0 +1,88 @@ +# The database config was lifted from https://dropwizard.github.io/dropwizard/0.7.1/docs/manual/jdbi.html +database: + # the name of your JDBC driver + driverClass: org.postgresql.Driver + + # the username + user: postgres + + # the password + password: test123 + + # the JDBC URL + # TODO: Probably want to programmatically set the database name. + url: jdbc:postgresql://127.0.0.1:5432/dcae_inv + + # any properties specific to your JDBC driver: + properties: + charSet: UTF-8 + + # the maximum amount of time to wait on an empty pool before throwing an exception + maxWaitForConnection: 1s + + # the SQL query to run when validating a connection's liveness + validationQuery: "/* MyService Health Check */ SELECT 1" + + # the minimum number of connections to keep open + minSize: 2 + + # the maximum number of connections to keep open + maxSize: 8 + + initialSize: 2 + + # whether or not idle connections should be validated + checkConnectionWhileIdle: false + + # the amount of time to sleep between runs of the idle connection validation, abandoned cleaner and idle pool resizing + evictionInterval: 10s + + # the minimum amount of time an connection must sit idle in the pool before it is eligible for eviction + minIdleTime: 1 minute + +databusControllerConnection: + host: databus-controller-hostname + port: 8443 + mechId: some-mech-id + password: some-password + +httpClient: + # The minimum number of threads to use for asynchronous calls. + minThreads: 1 + + # The maximum number of threads to use for asynchronous calls. + maxThreads: 128 + + # If true, the client will automatically decode response entities + # with gzip content encoding. + gzipEnabled: false + + # If true, the client will encode request entities with gzip + # content encoding. (Requires gzipEnabled to be true). + gzipEnabledForRequests: false + + # Requests to databus controller were timing out so I bumped it up 4x of default + timeout: 5000milliseconds + connectionTimeout: 5000milliseconds + +server: + # requestLog is for those messages you see right when the service handles HTTP requests + requestLog: + appenders: + - type: file + currentLogFilename: /opt/logs/DCAE/inventory/audit.log + archive: true + archivedLogFilenamePattern: /opt/logs/DCAE/inventory/audit-%d.log.gz + archivedFileCount: 10 + - type: console + +# Rolling is c.q.l.core.rolling.TimeBasedRollingPolicy +logging: + level: INFO + appenders: + - type: file + currentLogFilename: /opt/logs/DCAE/inventory/audit.log + archive: true + archivedLogFilenamePattern: /opt/logs/DCAE/inventory/audit-%d.log.gz + archivedFileCount: 10 + - type: console diff --git a/swagger_inventory.yaml b/swagger_inventory.yaml index 068f221..c18419c 100644 --- a/swagger_inventory.yaml +++ b/swagger_inventory.yaml @@ -17,7 +17,7 @@ # ECOMP is a trademark and service mark of AT&T Intellectual Property. swagger: '2.0' info: - version: "2.1.0" + version: "3.0.0" title: DCAE Inventory API description: | DCAE Inventory is a web service that provides the following: @@ -242,14 +242,6 @@ paths: description: "List of `DCAEService` objects" schema: $ref: "#/definitions/InlineResponse2001" - 502: - description: "Bad response from DCAE controller" - schema: - $ref: "#/definitions/ApiResponseMessage" - 504: - description: "Failed to connect with DCAE controller" - schema: - $ref: "#/definitions/ApiResponseMessage" /dcae-services-groupby/{propertyName}: get: summary: "" @@ -294,18 +286,10 @@ paths: description: "Single `DCAEService` object" schema: $ref: "#/definitions/DCAEService" - 502: - description: "Bad response from DCAE controller" - schema: - $ref: "#/definitions/ApiResponseMessage" 404: description: "DCAE service not found" schema: $ref: "#/definitions/ApiResponseMessage" - 504: - description: "Failed to connect with DCAE controller" - schema: - $ref: "#/definitions/ApiResponseMessage" put: summary: "" description: "Put a new or update an existing `DCAEService` object." @@ -425,7 +409,6 @@ definitions: description: "Specifies the name of the underying source service that is responsible\ \ for this components" enum: - - "DCAEController" - "DMaaPController" shareable: type: "integer" diff --git a/version.properties b/version.properties index 64dfa2c..fa21cfe 100644 --- a/version.properties +++ b/version.properties @@ -1,8 +1,8 @@ # Versioning variables # Note that these variables cannot be structured (e.g. : version.release or version.snapshot etc... ) # because they are used in Jenkins, whose plug-in doesn't support -major=1 -minor=1 +major=3 +minor=0 patch=0 base_version=${major}.${minor}.${patch} # Release must be completed with git revision # in Jenkins -- cgit 1.2.3-korg