diff options
Diffstat (limited to 'main')
29 files changed, 1587 insertions, 1386 deletions
diff --git a/main/pom.xml b/main/pom.xml index c4639dc5..ba217128 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -87,6 +87,10 @@ </dependency> <dependency> <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-webflux</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> @@ -129,6 +133,10 @@ <artifactId>mockito-junit-jupiter</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.springframework.security</groupId> + <artifactId>spring-security-test</artifactId> + </dependency> </dependencies> <build> <resources> diff --git a/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java b/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java index 802d37c8..8ac2da9f 100644 --- a/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java +++ b/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,14 +27,13 @@ import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; +@Setter @Getter @Component @ConfigurationProperties("policy-preload") public class PolicyPreloadConfig { - @Setter List<String> policyTypes; - @Setter List<String> policies; } diff --git a/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java b/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java index 074675b6..8f682e37 100644 --- a/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java +++ b/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,10 +42,9 @@ public class SecurityConfig { */ @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http - .httpBasic(Customizer.withDefaults()) + http.httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) - .csrf(AbstractHttpConfigurer::disable); + .csrf(AbstractHttpConfigurer::disable); // NOSONAR return http.build(); } } diff --git a/main/src/main/java/org/onap/policy/api/main/exception/ServiceExceptionHandler.java b/main/src/main/java/org/onap/policy/api/main/exception/ServiceExceptionHandler.java deleted file mode 100644 index 4b601439..00000000 --- a/main/src/main/java/org/onap/policy/api/main/exception/ServiceExceptionHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2022-2023 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.api.main.exception; - -import jakarta.ws.rs.core.Response; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.AfterThrowing; -import org.aspectj.lang.annotation.Aspect; -import org.onap.policy.models.base.PfModelRuntimeException; -import org.onap.policy.models.errors.concepts.ErrorResponse; -import org.springframework.stereotype.Component; -import org.springframework.transaction.TransactionException; - -@Aspect -@Component -public class ServiceExceptionHandler { - - /** - * Handle any exceptions that are not already handled. - * For e.g., runtime exceptions that could happen during SQL query execution related to data integrity etc. - * - * @param joinPoint the point of execution - * @param exception the exception - */ - @AfterThrowing(pointcut = "execution(* org.onap.policy.api.main.service.*.*(..))", throwing = "exception") - public void handleServiceException(JoinPoint joinPoint, RuntimeException exception) { - if (exception instanceof PolicyApiRuntimeException || exception instanceof PfModelRuntimeException) { - throw exception; - } else { - final var errorResponse = new ErrorResponse(); - errorResponse.setResponseCode(Response.Status.INTERNAL_SERVER_ERROR); - errorResponse.setErrorMessage(exception.getMessage()); - throw new PolicyApiRuntimeException(exception.getMessage(), exception.getCause(), errorResponse, null); - } - } - - /** - * Handle DB Transaction related exceptions. - * All service classes in org.onap.policy.api.main.service are transactional and autowiring these service classes - * can cause TransactionException. - * For e.g., JDBC connection failure occurs and failed to open transaction at service level - * - * @param joinPoint the point of execution - * @param exception the exception - */ - @AfterThrowing(pointcut = "execution(* org.onap.policy.api.main..*.*(..))", throwing = "exception") - public void handleTransactionException(JoinPoint joinPoint, TransactionException exception) { - final var errorResponse = new ErrorResponse(); - errorResponse.setResponseCode(Response.Status.INTERNAL_SERVER_ERROR); - errorResponse.setErrorMessage(exception.getMessage()); - throw new PolicyApiRuntimeException(exception.getMessage(), exception.getCause(), errorResponse, null); - } -} diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java index 9745ec94..3574545c 100755 --- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java @@ -4,7 +4,7 @@ * ================================================================================
* Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
* Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2023 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2024 Nordix Foundation.
* Modifications Copyright (C) 2020-2023 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -158,17 +158,12 @@ public class ApiRestController extends CommonRestController implements PolicyDes NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, "/policytypes", toJson(body));
}
try {
- mutex.acquire();
+ lock();
ToscaServiceTemplate serviceTemplate = toscaServiceTemplateService.createPolicyType(body);
- return makeOkResponse(requestId, serviceTemplate);
+ return makeCreatedResponse(requestId, serviceTemplate);
} catch (PfModelRuntimeException pfme) {
final var msg = "POST /policytypes";
throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId);
- } finally {
- mutex.release();
}
}
@@ -185,18 +180,13 @@ public class ApiRestController extends CommonRestController implements PolicyDes String versionId,
UUID requestId) {
try {
- mutex.acquire();
+ lock();
ToscaServiceTemplate serviceTemplate =
toscaServiceTemplateService.deletePolicyType(policyTypeId, versionId);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelRuntimeException pfme) {
var msg = String.format("DELETE /policytypes/%s/versions/%s", policyTypeId, versionId);
throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId);
- } finally {
- mutex.release();
}
}
@@ -322,18 +312,12 @@ public class ApiRestController extends CommonRestController implements PolicyDes "/policytypes/" + policyTypeId + "/versions/" + policyTypeVersion + "/policies", toJson(body));
}
try {
- mutex.acquire();
- ToscaServiceTemplate serviceTemplate =
- toscaServiceTemplateService.createPolicy(policyTypeId, policyTypeVersion, body);
- return makeOkResponse(requestId, serviceTemplate);
+ lock();
+ ToscaServiceTemplate serviceTemplate = toscaServiceTemplateService.createPolicy(body);
+ return makeCreatedResponse(requestId, serviceTemplate);
} catch (PfModelRuntimeException pfme) {
var msg = String.format("POST /policytypes/%s/versions/%s/policies", policyTypeId, policyTypeVersion);
throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId);
- } finally {
- mutex.release();
}
}
@@ -354,19 +338,14 @@ public class ApiRestController extends CommonRestController implements PolicyDes String policyVersion,
UUID requestId) {
try {
- mutex.acquire();
+ lock();
ToscaServiceTemplate serviceTemplate =
- toscaServiceTemplateService.deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);
+ toscaServiceTemplateService.deletePolicy(policyId, policyVersion);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelRuntimeException pfme) {
var msg = String.format("DELETE /policytypes/%s/versions/%s/policies/%s/versions/%s",
policyTypeId, policyTypeVersion, policyId, policyVersion);
throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId);
- } finally {
- mutex.release();
}
}
@@ -430,17 +409,12 @@ public class ApiRestController extends CommonRestController implements PolicyDes NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, "/policies", toJson(body));
}
try {
- mutex.acquire();
+ lock();
ToscaServiceTemplate serviceTemplate = toscaServiceTemplateService.createPolicies(body);
- return makeOkResponse(requestId, serviceTemplate);
+ return makeCreatedResponse(requestId, serviceTemplate);
} catch (PfModelRuntimeException pfme) {
final var msg = "POST /policies";
throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId);
- } finally {
- mutex.release();
}
}
@@ -457,18 +431,13 @@ public class ApiRestController extends CommonRestController implements PolicyDes String policyVersion,
UUID requestId) {
try {
- mutex.acquire();
+ lock();
ToscaServiceTemplate serviceTemplate =
- toscaServiceTemplateService.deletePolicy(null, null, policyId, policyVersion);
+ toscaServiceTemplateService.deletePolicy(policyId, policyVersion);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelRuntimeException pfme) {
var msg = String.format("DELETE /policies/%s/versions/%s", policyId, policyVersion);
throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId);
- } finally {
- mutex.release();
}
}
}
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java index d105058e..97fdb242 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java @@ -4,7 +4,7 @@ * ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
- * Modifications Copyright (C) 2022-2023 Nordix Foundation.
+ * Modifications Copyright (C) 2022-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ package org.onap.policy.api.main.rest;
+import jakarta.ws.rs.core.Response;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Semaphore;
@@ -31,6 +32,7 @@ import org.onap.policy.api.main.exception.PolicyApiRuntimeException; import org.onap.policy.common.utils.coder.Coder;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
+import org.onap.policy.models.errors.concepts.ErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
@@ -47,38 +49,11 @@ public class CommonRestController { private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestController.class);
- protected static final String EXTENSION_NAME = "interface info";
-
- protected static final String API_VERSION_NAME = "api-version";
protected static final String API_VERSION = "1.0.0";
-
- protected static final String LAST_MOD_NAME = "last-mod-release";
-
- protected static final String AUTHORIZATION_TYPE = "basicAuth";
-
protected static final String VERSION_MINOR_NAME = "X-MinorVersion";
- protected static final String VERSION_MINOR_DESCRIPTION =
- "Used to request or communicate a MINOR version back from the client"
- + " to the server, and from the server back to the client";
-
protected static final String VERSION_PATCH_NAME = "X-PatchVersion";
- protected static final String VERSION_PATCH_DESCRIPTION = "Used only to communicate a PATCH version in a "
- + "response for troubleshooting purposes only, and will not be provided by" + " the client on request";
-
protected static final String VERSION_LATEST_NAME = "X-LatestVersion";
- protected static final String VERSION_LATEST_DESCRIPTION = "Used only to communicate an API's latest version";
-
public static final String REQUEST_ID_NAME = "X-ONAP-RequestID";
- protected static final String REQUEST_ID_HDR_DESCRIPTION = "Used to track REST transactions for logging purpose";
- protected static final String REQUEST_ID_PARAM_DESCRIPTION = "RequestID for http transaction";
-
- protected static final String AUTHENTICATION_ERROR_MESSAGE = "Authentication Error";
- protected static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error";
- protected static final String SERVER_ERROR_MESSAGE = "Internal Server Error";
- protected static final String NOT_FOUND_MESSAGE = "Resource Not Found";
- protected static final String INVALID_BODY_MESSAGE = "Invalid Body";
- protected static final String INVALID_PAYLOAD_MESSAGE = "Not Acceptable Payload";
- protected static final String HTTP_CONFLICT_MESSAGE = "Delete Conflict, Rule Violation";
protected static final String ERROR_MESSAGE_NO_POLICIES_FOUND = "No policies found";
protected final Coder coder = new StandardCoder();
@@ -87,6 +62,10 @@ public class CommonRestController { return makeResponse(requestId, respEntity, HttpStatus.OK.value());
}
+ protected <T> ResponseEntity<T> makeCreatedResponse(UUID requestId, T respEntity) {
+ return makeResponse(requestId, respEntity, HttpStatus.CREATED.value());
+ }
+
protected <T> ResponseEntity<T> makeResponse(UUID requestId, T respEntity, int status) {
return CommonRestController
.addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(status)), requestId)
@@ -137,6 +116,20 @@ public class CommonRestController { }
}
+ protected void lock() throws PolicyApiRuntimeException {
+ try {
+ mutex.acquire();
+ } catch (InterruptedException exception) {
+ Thread.currentThread().interrupt();
+ final var errorResponse = new ErrorResponse();
+ errorResponse.setResponseCode(Response.Status.INTERNAL_SERVER_ERROR);
+ errorResponse.setErrorMessage(exception.getMessage());
+ throw new PolicyApiRuntimeException(exception.getMessage(), exception.getCause(), errorResponse, null);
+ } finally {
+ mutex.release();
+ }
+ }
+
@ExceptionHandler(value = {PolicyApiRuntimeException.class})
protected ResponseEntity<Object> handleException(PolicyApiRuntimeException ex, WebRequest req) {
LOGGER.warn(ex.getMessage(), ex.getCause());
diff --git a/main/src/main/java/org/onap/policy/api/main/rest/NodeTemplateController.java b/main/src/main/java/org/onap/policy/api/main/rest/NodeTemplateController.java index 944a6f85..e76dba56 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/NodeTemplateController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/NodeTemplateController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy API * ================================================================================ - * Copyright (C) 2022 Nordix Foundation. + * Copyright (C) 2022, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,17 +63,12 @@ public class NodeTemplateController extends CommonRestController implements Tosc toJson(body)); } try { - mutex.acquire(); + lock(); ToscaServiceTemplate nodeTemplates = toscaServiceTemplateService.createToscaNodeTemplates(body); - return makeOkResponse(requestId, nodeTemplates); + return makeCreatedResponse(requestId, nodeTemplates); } catch (PfModelException | PfModelRuntimeException pfme) { final var msg = "POST /nodetemplates"; throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId); - } finally { - mutex.release(); } } @@ -92,17 +87,12 @@ public class NodeTemplateController extends CommonRestController implements Tosc toJson(body)); } try { - mutex.acquire(); + lock(); ToscaServiceTemplate nodeTemplates = toscaServiceTemplateService.updateToscaNodeTemplates(body); return makeOkResponse(requestId, nodeTemplates); } catch (PfModelException | PfModelRuntimeException pfme) { final var msg = "PUT /nodetemplates"; throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId); - } finally { - mutex.release(); } } @@ -116,17 +106,12 @@ public class NodeTemplateController extends CommonRestController implements Tosc @Override public ResponseEntity<ToscaServiceTemplate> deleteToscaNodeTemplates(String name, String version, UUID requestId) { try { - mutex.acquire(); + lock(); ToscaServiceTemplate nodeTemplates = toscaServiceTemplateService.deleteToscaNodeTemplate(name, version); return makeOkResponse(requestId, nodeTemplates); } catch (PfModelException | PfModelRuntimeException pfme) { final var msg = String.format("DELETE /nodetemplates/%s/versions/%s", name, version); throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new PolicyApiRuntimeException(e.getMessage(), null, null, requestId); - } finally { - mutex.release(); } } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/PolicyFetchMode.java b/main/src/main/java/org/onap/policy/api/main/rest/PolicyFetchMode.java index 7e201b63..a25c80ca 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/PolicyFetchMode.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/PolicyFetchMode.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. + * Copyright (C) 2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,15 +23,5 @@ package org.onap.policy.api.main.rest; public enum PolicyFetchMode { BARE, - REFERENCED; - - /** - * Convert a string to this ENUM. - * - * @param modeString the incoming string value - * @return the enum value of the string - */ - public static PolicyFetchMode fromString(final String modeString) { - return valueOf(modeString.toUpperCase()); - } + REFERENCED } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/stub/ApiRestControllerStub.java b/main/src/main/java/org/onap/policy/api/main/rest/stub/ApiRestControllerStub.java index 49c9bf45..4d75b00d 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/stub/ApiRestControllerStub.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/stub/ApiRestControllerStub.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2023 Nordix Foundation. + * Copyright (C) 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -43,7 +43,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic @Override public ResponseEntity<ToscaServiceTemplate> createPolicies( @Valid ToscaServiceTemplate body, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getCreateStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -52,13 +52,13 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyTypeVersion, @Valid ToscaServiceTemplate body, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getCreateStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<ToscaServiceTemplate> createPolicyType( @Valid ToscaServiceTemplate body, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getCreateStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -66,7 +66,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyId, String policyVersion, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -76,7 +76,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyId, String policyVersion, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -84,7 +84,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyTypeId, String versionId, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -93,13 +93,13 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyTypeVersion, @Valid PolicyFetchMode mode, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<ToscaServiceTemplate> getAllPolicyTypes( UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -109,19 +109,19 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyTypeVersion, @Valid PolicyFetchMode mode, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<ToscaServiceTemplate> getAllVersionsOfPolicyType( String policyTypeId, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<HealthCheckReport> getHealthCheck( UUID requestID) { - return stubUtils.getStubbedResponse(HealthCheckReport.class); + return stubUtils.getOkStubbedResponse(HealthCheckReport.class); } @Override @@ -131,19 +131,19 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyTypeVersion, @Valid PolicyFetchMode mode, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<ToscaServiceTemplate> getLatestVersionOfPolicyType( String policyTypeId, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<ToscaServiceTemplate> getPolicies( @Valid PolicyFetchMode mode, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -152,7 +152,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyVersion, @Valid PolicyFetchMode mode, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -163,7 +163,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyVersion, @Valid PolicyFetchMode mode, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -171,7 +171,7 @@ public class ApiRestControllerStub extends CommonRestController implements Polic String policyTypeId, String versionId, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/stub/NodeTemplateControllerStub.java b/main/src/main/java/org/onap/policy/api/main/rest/stub/NodeTemplateControllerStub.java index 5045eb69..ee39c7ef 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/stub/NodeTemplateControllerStub.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/stub/NodeTemplateControllerStub.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2023 Nordix Foundation. + * Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,13 +43,13 @@ public class NodeTemplateControllerStub extends CommonRestController @Override public ResponseEntity<ToscaServiceTemplate> createToscaNodeTemplates( @Valid ToscaServiceTemplate body, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getCreateStubbedResponse(ToscaServiceTemplate.class); } @Override public ResponseEntity<ToscaServiceTemplate> deleteToscaNodeTemplates( String name, String version, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } @Override @@ -67,6 +67,6 @@ public class NodeTemplateControllerStub extends CommonRestController @Override public ResponseEntity<ToscaServiceTemplate> updateToscaNodeTemplates( @Valid ToscaServiceTemplate body, UUID requestID) { - return stubUtils.getStubbedResponse(ToscaServiceTemplate.class); + return stubUtils.getOkStubbedResponse(ToscaServiceTemplate.class); } } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/stub/StubUtils.java b/main/src/main/java/org/onap/policy/api/main/rest/stub/StubUtils.java index 62f091cb..5cccb7e3 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/stub/StubUtils.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/stub/StubUtils.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2023 Nordix Foundation. + * Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,22 +39,41 @@ import org.springframework.stereotype.Service; @Profile("stub") class StubUtils { private static final Logger log = LoggerFactory.getLogger(StubUtils.class); + private static final String APPLICATION_JSON = "application/json"; + private static final String COULDNT_SERIALIZE_RESPONSE_ERROR = + "Couldn't serialize response for content type application/json"; private final HttpServletRequest request; private static final String ACCEPT = "Accept"; private static final String TOSCA_NODE_TEMPLATE_RESOURCE = "nodetemplates/nodetemplates.metadatasets.input.tosca.json"; private static final Gson JSON_TRANSLATOR = new Gson(); - <T> ResponseEntity<T> getStubbedResponse(Class<T> clazz) { + <T> ResponseEntity<T> getCreateStubbedResponse(Class<T> clazz) { var accept = request.getHeader(ACCEPT); - if (accept != null && accept.contains("application/json")) { + if (accept != null && accept.contains(APPLICATION_JSON)) { + final var resource = new ClassPathResource(TOSCA_NODE_TEMPLATE_RESOURCE); + try (var inputStream = resource.getInputStream()) { + final var string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); + var targetObject = JSON_TRANSLATOR.fromJson(string, clazz); + return new ResponseEntity<>(targetObject, HttpStatus.CREATED); + } catch (IOException e) { + log.error(COULDNT_SERIALIZE_RESPONSE_ERROR, e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + } + + <T> ResponseEntity<T> getOkStubbedResponse(Class<T> clazz) { + var accept = request.getHeader(ACCEPT); + if (accept != null && accept.contains(APPLICATION_JSON)) { final var resource = new ClassPathResource(TOSCA_NODE_TEMPLATE_RESOURCE); try (var inputStream = resource.getInputStream()) { final var string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); var targetObject = JSON_TRANSLATOR.fromJson(string, clazz); return new ResponseEntity<>(targetObject, HttpStatus.OK); } catch (IOException e) { - log.error("Couldn't serialize response for content type application/json", e); + log.error(COULDNT_SERIALIZE_RESPONSE_ERROR, e); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -63,14 +82,14 @@ class StubUtils { <T> ResponseEntity<List<T>> getStubbedResponseList(Class<T> clazz) { var accept = request.getHeader(ACCEPT); - if (accept != null && accept.contains("application/json")) { + if (accept != null && accept.contains(APPLICATION_JSON)) { final var resource = new ClassPathResource(TOSCA_NODE_TEMPLATE_RESOURCE); try (var inputStream = resource.getInputStream()) { final var string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); var targetObject = List.of(JSON_TRANSLATOR.fromJson(string, clazz)); return new ResponseEntity<>(targetObject, HttpStatus.OK); } catch (IOException e) { - log.error("Couldn't serialize response for content type application/json", e); + log.error(COULDNT_SERIALIZE_RESPONSE_ERROR, e); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } diff --git a/main/src/main/java/org/onap/policy/api/main/service/PdpGroupService.java b/main/src/main/java/org/onap/policy/api/main/service/PdpGroupService.java index e9d84be5..234b90a2 100644 --- a/main/src/main/java/org/onap/policy/api/main/service/PdpGroupService.java +++ b/main/src/main/java/org/onap/policy/api/main/service/PdpGroupService.java @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ package org.onap.policy.api.main.service; import jakarta.ws.rs.core.Response; import java.util.List; -import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.onap.policy.api.main.repository.PdpGroupRepository; import org.onap.policy.models.base.PfModelRuntimeException; @@ -43,16 +42,17 @@ public class PdpGroupService { /** * Fetch all the PDP groups from the DB. + * * @return a list of {@link PdpGroup} */ private List<PdpGroup> getAllPdpGroups() { - return pdpGroupRepository.findAll().stream().map(JpaPdpGroup::toAuthorative).collect(Collectors.toList()); + return pdpGroupRepository.findAll().stream().map(JpaPdpGroup::toAuthorative).toList(); } /** * Assert that the policy type is not supported in any PDP group. * - * @param policyTypeName the policy type name + * @param policyTypeName the policy type name * @param policyTypeVersion the policy type version * @throws PfModelRuntimeException if the policy type is supported in a PDP group */ @@ -73,7 +73,7 @@ public class PdpGroupService { /** * Assert that the policy is not deployed in a PDP group. * - * @param policyName the policy name + * @param policyName the policy name * @param policyVersion the policy version * @throws PfModelRuntimeException thrown if the policy is deployed in a PDP group */ diff --git a/main/src/main/java/org/onap/policy/api/main/service/ToscaServiceTemplateService.java b/main/src/main/java/org/onap/policy/api/main/service/ToscaServiceTemplateService.java index 9ec28d1b..9817df73 100644 --- a/main/src/main/java/org/onap/policy/api/main/service/ToscaServiceTemplateService.java +++ b/main/src/main/java/org/onap/policy/api/main/service/ToscaServiceTemplateService.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022-2023 Nordix Foundation. + * Modifications Copyright (C) 2022-2024 Nordix Foundation. * ================================================================================ * 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 ToscaServiceTemplateService { /** * Retrieves a list of policy types matching specified policy type name and version. * - * @param policyTypeName the name of policy type + * @param policyTypeName the name of policy type * @param policyTypeVersion the version of policy type * @return the ToscaServiceTemplate object */ @@ -123,11 +123,11 @@ public class ToscaServiceTemplateService { incomingServiceTemplate)).orElse(incomingServiceTemplate); final var result = serviceTemplateToWrite.validate("service template"); - if (!result.isValid()) { - throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, result.getResult()); - } else { + if (result.isValid()) { toscaServiceTemplateRepository.save(serviceTemplateToWrite); LOGGER.debug("<-createPolicyType: writtenServiceTemplate={}", serviceTemplateToWrite); + } else { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, result.getResult()); } return body; } @@ -135,7 +135,7 @@ public class ToscaServiceTemplateService { /** * Delete the policy type matching specified policy type name and version. * - * @param policyTypeName the name of policy type + * @param policyTypeName the name of policy type * @param policyTypeVersion the version of policy type, if the version of the key is null, * all versions of the policy type are deleted. * @return the TOSCA service template containing the policy types that were deleted @@ -202,31 +202,33 @@ public class ToscaServiceTemplateService { /** * Retrieves a list of policies matching specified name and version of both policy type and policy. * - * @param policyTypeName the name of policy type + * @param policyTypeName the name of policy type * @param policyTypeVersion the version of policy type - * @param policyName the name of policy - * @param policyVersion the version of policy - * @param mode the fetch mode for policies + * @param policyName the name of policy + * @param policyVersion the version of policy + * @param mode the fetch mode for policies * @return the ToscaServiceTemplate object with the policies found * @throws PfModelException on errors getting the policy */ public ToscaServiceTemplate fetchPolicies(final String policyTypeName, final String policyTypeVersion, - final String policyName, final String policyVersion, final PolicyFetchMode mode) throws PfModelException { + final String policyName, final String policyVersion, + final PolicyFetchMode mode) throws PfModelException { return getFilteredPolicies(policyTypeName, policyTypeVersion, policyName, policyVersion, mode); } /** * Retrieves a list of policies with the latest versions that match specified policy type id and version. * - * @param policyTypeName the name of policy type + * @param policyTypeName the name of policy type * @param policyTypeVersion the version of policy type - * @param policyName the name of the policy - * @param mode the fetch mode for policies + * @param policyName the name of the policy + * @param mode the fetch mode for policies * @return the ToscaServiceTemplate object with the policies found * @throws PfModelException on errors getting the policy */ public ToscaServiceTemplate fetchLatestPolicies(final String policyTypeName, final String policyTypeVersion, - final String policyName, final PolicyFetchMode mode) throws PfModelException { + final String policyName, final PolicyFetchMode mode) + throws PfModelException { return getFilteredPolicies(policyTypeName, policyTypeVersion, policyName, ToscaTypedEntityFilter.LATEST_VERSION, mode); } @@ -234,14 +236,11 @@ public class ToscaServiceTemplateService { /** * Creates one or more new policies for the same policy type name and version. * - * @param policyTypeName the name of policy type - * @param policyTypeVersion the version of policy type * @param body the entity body of polic(ies) * @return the ToscaServiceTemplate object containing the policy types that were created * @throws PfModelRuntimeException on errors creating the policy */ - public ToscaServiceTemplate createPolicy(final String policyTypeName, final String policyTypeVersion, - final ToscaServiceTemplate body) throws PfModelRuntimeException { + public ToscaServiceTemplate createPolicy(final ToscaServiceTemplate body) throws PfModelRuntimeException { return createPolicies(body); } @@ -279,15 +278,13 @@ public class ToscaServiceTemplateService { /** * Deletes the policy matching specified name and version of both policy type and policy. * - * @param policyTypeName the name of policy type - * @param policyTypeVersion the version of policy type - * @param policyName the name of policy + * @param policyName the name of policy * @param policyVersion the version of policy * @return the ToscaServiceTemplate object containing the policies that were deleted * @throws PfModelRuntimeException on errors deleting the policy */ - public ToscaServiceTemplate deletePolicy(final String policyTypeName, final String policyTypeVersion, - final String policyName, final String policyVersion) throws PfModelRuntimeException { + public ToscaServiceTemplate deletePolicy(final String policyName, final String policyVersion) + throws PfModelRuntimeException { final var policyKey = new PfConceptKey(policyName, policyVersion); LOGGER.debug("->deletePolicy: name={}, version={}", policyName, policyVersion); @@ -375,14 +372,15 @@ public class ToscaServiceTemplateService { /** * Retrieves TOSCA service template with the specified version of the policy. * - * @param policyName the name of the policy + * @param policyName the name of the policy * @param policyVersion the version of the policy - * @param mode the fetch mode for policies + * @param mode the fetch mode for policies * @return the TOSCA service template containing the specified version of the policy * @throws PfModelException on errors getting the policy */ private ToscaServiceTemplate getFilteredPolicies(final String policyTypeName, final String policyTypeVersion, - final String policyName, final String policyVersion, final PolicyFetchMode mode) throws PfModelException { + final String policyName, final String policyVersion, + final PolicyFetchMode mode) throws PfModelException { final var policyFilter = ToscaTypedEntityFilter.<ToscaPolicy>builder() .name(policyName).version(policyVersion).type(policyTypeName).typeVersion(policyTypeVersion).build(); final var dbServiceTemplate = getDefaultJpaToscaServiceTemplate(); @@ -448,7 +446,7 @@ public class ToscaServiceTemplateService { for (JpaToscaNodeTemplate nodeTemplate : incomingServiceTemplate.getTopologyTemplate().getNodeTemplates() .getAll(null)) { // verify node types in the db if mismatch/empty entities in the template - if (! (nodeTypes.isPresent() && nodeTypes.get().getKeys().contains(nodeTemplate.getType()))) { + if (!(nodeTypes.isPresent() && nodeTypes.get().getKeys().contains(nodeTemplate.getType()))) { nodeTemplateService.verifyNodeTypeInDbTemplate(nodeTemplate); } } @@ -489,7 +487,7 @@ public class ToscaServiceTemplateService { /** * Delete a tosca node template. * - * @param name the name of node template + * @param name the name of node template * @param version the version of node template * @return the TOSCA service template containing the node template that were deleted * @throws PfModelException on errors deleting node templates @@ -534,7 +532,7 @@ public class ToscaServiceTemplateService { /** * Get tosca node templates. * - * @param name the name of the node template to get, set to null to get all node templates + * @param name the name of the node template to get, set to null to get all node templates * @param version the version of the node template to get, set to null to get all versions * @return the node templates with the specified key * @throws PfModelException on errors getting node templates @@ -568,7 +566,7 @@ public class ToscaServiceTemplateService { * Get Service Template. * * @return the Service Template read from the database - * @throws PfModelRuntimeException if service template if not found in database. + * @throws PfModelRuntimeException if service template not found in database. */ public JpaToscaServiceTemplate getDefaultJpaToscaServiceTemplate() throws PfModelRuntimeException { final var defaultServiceTemplateOpt = getDefaultJpaToscaServiceTemplateOpt(); diff --git a/main/src/test/java/org/onap/policy/api/contract/ApiContractTest.java b/main/src/test/java/org/onap/policy/api/contract/ApiContractTest.java index 08cb7f18..aa43e461 100644 --- a/main/src/test/java/org/onap/policy/api/contract/ApiContractTest.java +++ b/main/src/test/java/org/onap/policy/api/contract/ApiContractTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2023 Nordix Foundation. + * Copyright (C) 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,119 +21,112 @@ package org.onap.policy.api.contract; -import static org.junit.Assert.assertEquals; - -import jakarta.ws.rs.core.Response; -import java.io.IOException; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.onap.policy.api.main.PolicyApiApplication; -import org.onap.policy.api.main.rest.utils.CommonTestRestController; -import org.onap.policy.common.utils.security.SelfSignedKeyStore; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.client.ExchangeFilterFunctions; @SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({"test", "stub"}) +@AutoConfigureWebTestClient @DirtiesContext(classMode = ClassMode.AFTER_CLASS) -class ApiContractTest extends CommonTestRestController { - protected static final String APP_JSON = "application/json"; - protected static final String APP_YAML = "application/yaml"; - private static final String TOSCA_NODE_TEMPLATE_RESOURCE = - "nodetemplates/nodetemplates.metadatasets.input.tosca.json"; +class ApiContractTest { - @LocalServerPort - private int apiPort; + @Autowired + WebTestClient webClient; - private static SelfSignedKeyStore keystore; + protected static final MediaType APPLICATION_YAML = new MediaType("application", "yaml"); + protected static final MediaType APPLICATION_JSON = new MediaType("application", "json"); - @BeforeAll - public static void setupParameters() throws IOException, InterruptedException { - keystore = new SelfSignedKeyStore(); - } + private static final String TOSCA_NODE_TEMPLATE_RESOURCE = + "nodetemplates/nodetemplates.metadatasets.input.tosca.json"; - @DynamicPropertySource - static void registerPgProperties(DynamicPropertyRegistry registry) { - registry.add("server.ssl.enabled", () -> "true"); - registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); - registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); - registry.add("server.ssl.key-store-type", () -> "PKCS12"); - registry.add("server.ssl.key-alias", () -> "policy@policy.onap.org"); - registry.add("server.ssl.key-password", () -> SelfSignedKeyStore.PRIVATE_KEY_PASSWORD); + @BeforeEach + void beforeEach() { + var filter = ExchangeFilterFunctions.basicAuthentication("policyadmin", "zb!XztG34"); + webClient = webClient.mutate().filter(filter).build(); } @Test - void testStubPolicyDesign() throws Exception { - checkStubJsonGet("policies"); - checkStubJsonGet("policies/policyname/versions/1.0.2"); - checkStubJsonGet("policytypes"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/latest"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + void testStubPolicyDesign() { + checkStubJsonGet("/policies"); + checkStubJsonGet("/policies/policyname/versions/1.0.2"); + checkStubJsonGet("/policytypes"); + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16"); + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/latest"); + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0"); + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies"); + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + "9c65fa1f-2833-4076-a64d-5b62e35cd09b"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + "9c65fa1f-2833-4076-a64d-5b62e35cd09b/versions/latest"); - checkStubJsonGet("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + checkStubJsonGet("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + "9c65fa1f-2833-4076-a64d-5b62e35cd09b/versions/1.2.3"); - checkStubJsonGet("healthcheck"); + checkStubJsonGet("/healthcheck"); - checkStubJsonPost("policies"); - checkStubJsonPost("policytypes"); - checkStubJsonPost("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.2.3/policies"); + checkStubJsonPost("/policies"); + checkStubJsonPost("/policytypes"); + checkStubJsonPost("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.2.3/policies"); - checkStubJsonDelete("policies/policyname/versions/1.0.2"); - checkStubJsonDelete("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0"); - checkStubJsonDelete("policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + checkStubJsonDelete("/policies/policyname/versions/1.0.2"); + checkStubJsonDelete("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0"); + checkStubJsonDelete("/policytypes/380d5cb1-e43d-45b7-b10b-ebd15dfabd16/versions/1.0.0/policies/" + "9c65fa1f-2833-4076-a64d-5b62e35cd09b/versions/1.2.3"); } @Test - void testStubNodeTemplateDesign() throws Exception { - checkStubJsonGet("nodetemplates"); - checkStubJsonGet("nodetemplates/k8stemplate/versions/1.0.0"); - - checkStubJsonPost("nodetemplates"); - - checkStubJsonPut("nodetemplates"); - - checkStubJsonDelete("nodetemplates/k8stemplate/versions/1.0.0"); + void testStubNodeTemplateDesign() { + checkStubJsonGet("/nodetemplates"); + checkStubJsonGet("/nodetemplates/k8stemplate/versions/1.0.0"); + checkStubJsonPost("/nodetemplates"); + checkStubJsonPut(); + checkStubJsonDelete("/nodetemplates/k8stemplate/versions/1.0.0"); } @Test - void testErrors() throws Exception { - var responseYaml = super.readResource("policies", APP_YAML, apiPort); - assertEquals(Response.Status.NOT_IMPLEMENTED.getStatusCode(), responseYaml.getStatus()); + void testErrors() { + webClient.get().uri("/policies").accept(APPLICATION_YAML) + .exchange().expectStatus().isEqualTo(HttpStatus.NOT_IMPLEMENTED); - var responseListYaml = super.readResource("nodetemplates", APP_YAML, apiPort); - assertEquals(Response.Status.NOT_IMPLEMENTED.getStatusCode(), responseListYaml.getStatus()); + webClient.get().uri("/nodetemplates").accept(APPLICATION_YAML) + .exchange().expectStatus().isEqualTo(HttpStatus.NOT_IMPLEMENTED); } - private void checkStubJsonGet(String url) throws Exception { - var response = super.readResource(url, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + private void checkStubJsonGet(String url) { + webClient.get().uri(url).accept(APPLICATION_JSON) + .exchange().expectStatus().isOk(); } - private void checkStubJsonPost(String url) throws Exception { - var response = super.createResource(url, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + private void checkStubJsonPost(String url) { + var body = ResourceUtils.getResourceAsString(TOSCA_NODE_TEMPLATE_RESOURCE); + webClient.post().uri(url) + .contentType(MediaType.APPLICATION_JSON).bodyValue(body) + .accept(APPLICATION_JSON) + .exchange().expectStatus().isCreated(); } - private void checkStubJsonPut(String url) throws Exception { - var response = super.updateResource(url, TOSCA_NODE_TEMPLATE_RESOURCE, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + private void checkStubJsonPut() { + var body = ResourceUtils.getResourceAsString(TOSCA_NODE_TEMPLATE_RESOURCE); + webClient.put().uri("/nodetemplates") + .contentType(APPLICATION_JSON).bodyValue(body) + .accept(APPLICATION_JSON) + .exchange().expectStatus().isOk(); } - private void checkStubJsonDelete(String url) throws Exception { - var response = super.deleteResource(url, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + private void checkStubJsonDelete(String url) { + webClient.delete().uri(url).accept(APPLICATION_JSON) + .exchange().expectStatus().isOk(); } } diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestController.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestController.java new file mode 100644 index 00000000..47e3f20a --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestController.java @@ -0,0 +1,383 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; +import org.onap.policy.api.main.rest.provider.healthcheck.HealthCheckProvider; +import org.onap.policy.api.main.service.ToscaServiceTemplateService; +import org.onap.policy.common.endpoints.report.HealthCheckReport; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@WebMvcTest(controllers = ApiRestController.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +@ActiveProfiles({"default", "test-mvc"}) +class TestApiRestController { + + @Autowired + private MockMvc mvc; + + @MockBean + private HealthCheckProvider healthCheckProvider; + + @MockBean + private ToscaServiceTemplateService toscaServiceTemplateService; + + AutoCloseable autoCloseable; + + private final PfModelRuntimeException pfException = + new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Error"); + + private static final String SOME_POLICY_TYPE = "somePolicyType"; + private static final String SOME_POLICY_NAME = "somePolicyName"; + private static final String SOME_POLICY_TYPE_VERSION = "somePolicyTypeVersion"; + private static final String SOME_POLICY_VERSION = "somePolicyVersion"; + private static final String WRONG_POLICY_EVERYTHING = "wrong"; + + private static final String URI_VALID_POLICY_TYPE_AND_VERSION = + "/policytypes/" + SOME_POLICY_TYPE + "/versions/" + SOME_POLICY_TYPE_VERSION; + private static final String URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES = + URI_VALID_POLICY_TYPE_AND_VERSION + "/policies"; + + @BeforeEach + void setUp(@Autowired WebApplicationContext context) { + autoCloseable = MockitoAnnotations.openMocks(this); + this.mvc = MockMvcBuilders.webAppContextSetup(context).build(); + } + + @AfterEach + void tearDown() throws Exception { + autoCloseable.close(); + } + + @Test + void getHealthCheck() throws Exception { + var healthCheckReport = new HealthCheckReport(); + healthCheckReport.setCode(200); + healthCheckReport.setHealthy(true); + healthCheckReport.setMessage("Health check OK"); + healthCheckReport.setUrl("/healthcheck"); + given(healthCheckProvider.performHealthCheck()).willReturn(healthCheckReport); + var response = "{\"url\":\"/healthcheck\",\"healthy\":true,\"code\":200,\"message\":\"Health check OK\"}"; + + var getRequest = get("/healthcheck").accept(MediaType.APPLICATION_JSON_VALUE); + mvc.perform(getRequest).andExpect(status().isOk()).andExpect(content().string(response)); + } + + @Test + void getAllPolicyTypes() throws Exception { + var policyType = new ToscaServiceTemplate(); + when(toscaServiceTemplateService.fetchPolicyTypes(null, null)).thenReturn(policyType); + var getRequest = get("/policytypes").accept(MediaType.APPLICATION_JSON_VALUE); + this.mvc.perform(getRequest).andExpect(status().isOk()); + + given(toscaServiceTemplateService.fetchPolicyTypes(null, null)).willThrow(pfException); + var getExceptionReq = get("/policytypes").accept(MediaType.APPLICATION_JSON_VALUE); + this.mvc.perform(getExceptionReq).andExpect(status().isBadRequest()); + } + + @Test + void getAllVersionsOfPolicyType() throws Exception { + when(toscaServiceTemplateService.fetchPolicyTypes(SOME_POLICY_TYPE, null)) + .thenReturn(new ToscaServiceTemplate()); + var getRequest = get("/policytypes").accept(MediaType.APPLICATION_JSON_VALUE); + this.mvc.perform(getRequest).andExpect(status().isOk()); + + given(toscaServiceTemplateService.fetchPolicyTypes(WRONG_POLICY_EVERYTHING, null)) + .willThrow(pfException); + this.mvc.perform(get("/policytypes/wrong").accept(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isBadRequest()); + } + + @Test + void getSpecificVersionOfPolicyType() throws Exception { + when(toscaServiceTemplateService.fetchPolicyTypes(SOME_POLICY_TYPE, SOME_POLICY_TYPE_VERSION)) + .thenReturn(new ToscaServiceTemplate()); + this.mvc.perform(get(URI_VALID_POLICY_TYPE_AND_VERSION) + .accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()); + + when(toscaServiceTemplateService.fetchPolicyTypes(WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING)) + .thenThrow(new PfModelException(Response.Status.BAD_REQUEST, "Bad Request")); + this.mvc.perform(get("/policytypes/wrong/versions/wrong") + .accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isBadRequest()); + } + + @Test + void getLatestVersionOfPolicyType() throws Exception { + when(toscaServiceTemplateService.fetchLatestPolicyTypes(SOME_POLICY_TYPE)) + .thenReturn(new ToscaServiceTemplate()); + this.mvc.perform(get("/policytypes/somePolicyType/versions/latest") + .accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()); + + given(toscaServiceTemplateService.fetchLatestPolicyTypes(WRONG_POLICY_EVERYTHING)).willThrow(pfException); + this.mvc.perform(get("/policytypes/wrong/versions/latest") + .accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isBadRequest()); + } + + @Test + void createPolicyType() throws Exception { + var toscaTemplate = new ToscaServiceTemplate(); + toscaTemplate.setName(SOME_POLICY_TYPE); + toscaTemplate.setVersion(SOME_POLICY_TYPE_VERSION); + when(toscaServiceTemplateService.createPolicyType(any())).thenReturn(toscaTemplate); + + var body = ResourceUtils.getResourceAsString("policytypes/onap.policies.Test.yaml"); + var postRequest = post("/policytypes").content(body).contentType("application/yaml"); + this.mvc.perform(postRequest).andExpect(status().isCreated()); + } + + @Test + void createPolicyType_Exception() throws Exception { + when(toscaServiceTemplateService.createPolicyType(any())) + .thenThrow(new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Bad Request")); + + var body = ResourceUtils.getResourceAsString("policytypes/onap.policies.Test.yaml"); + var postRequest = post("/policytypes").content(body).contentType("application/yaml"); + this.mvc.perform(postRequest).andExpect(status().isBadRequest()); + } + + @Test + void deleteSpecificVersionOfPolicyType() throws Exception { + when(toscaServiceTemplateService.deletePolicyType(SOME_POLICY_TYPE, SOME_POLICY_TYPE_VERSION)) + .thenReturn(new ToscaServiceTemplate()); + var deleteRequest = delete(URI_VALID_POLICY_TYPE_AND_VERSION) + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(deleteRequest).andExpect(status().isOk()); + } + + @Test + void deleteSpecificVersionOfPolicyType_Exception() throws Exception { + when(toscaServiceTemplateService.deletePolicyType(WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING)) + .thenThrow(new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Error")); + var deleteExceptionReq = delete("/policytypes/wrong/versions/wrong") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(deleteExceptionReq).andExpect(status().isBadRequest()); + } + + @Test + void getAllPolicies() throws Exception { + when(toscaServiceTemplateService.fetchPolicies( + SOME_POLICY_TYPE, SOME_POLICY_TYPE_VERSION, null, null, PolicyFetchMode.BARE)) + .thenReturn(new ToscaServiceTemplate()); + var fetchPoliciesReq = get(URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES) + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesReq).andExpect(status().isOk()); + + given(toscaServiceTemplateService.fetchPolicies( + WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, null, null, PolicyFetchMode.REFERENCED)) + .willThrow(pfException); + var fetchPoliciesExcReq = get("/policytypes/wrong/versions/wrong/policies?mode=REFERENCED") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isBadRequest()); + } + + @Test + void getAllVersionsOfPolicy() throws Exception { + when(toscaServiceTemplateService.fetchPolicies( + SOME_POLICY_TYPE, SOME_POLICY_TYPE_VERSION, SOME_POLICY_NAME, null, PolicyFetchMode.BARE)) + .thenReturn(new ToscaServiceTemplate()); + var fetchPoliciesReq = get(URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES + "/somePolicyName") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesReq).andExpect(status().isOk()); + } + + @Test + void getAllVersionsOfPolicy_Exception() throws Exception { + given(toscaServiceTemplateService.fetchPolicies( + WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, + null, PolicyFetchMode.REFERENCED)).willThrow(pfException); + var fetchPoliciesExcReq = get("/policytypes/wrong/versions/wrong/policies/wrong?mode=REFERENCED") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isBadRequest()); + } + + @Test + void getSpecificVersionOfPolicy() throws Exception { + when(toscaServiceTemplateService.fetchPolicies( + SOME_POLICY_TYPE, SOME_POLICY_TYPE_VERSION, SOME_POLICY_NAME, SOME_POLICY_VERSION, PolicyFetchMode.BARE)) + .thenReturn(new ToscaServiceTemplate()); + var fetchPoliciesReq = + get(URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES + + "/somePolicyName/versions/somePolicyVersion").accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesReq).andExpect(status().isOk()); + + given(toscaServiceTemplateService.fetchPolicies( + WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, + WRONG_POLICY_EVERYTHING, PolicyFetchMode.REFERENCED)).willThrow(pfException); + var fetchPoliciesExcReq = get("/policytypes/wrong/versions/wrong/policies/wrong/versions/wrong" + + "?mode=REFERENCED").accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isBadRequest()); + } + + @Test + void getLatestVersionOfPolicy() throws Exception { + when(toscaServiceTemplateService.fetchLatestPolicies( + SOME_POLICY_TYPE, SOME_POLICY_TYPE_VERSION, SOME_POLICY_NAME, PolicyFetchMode.BARE)) + .thenReturn(new ToscaServiceTemplate()); + var fetchPoliciesReq = get(URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES + + "/somePolicyName/versions/latest").accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesReq).andExpect(status().isOk()); + } + + @Test + void getLatestVersionOfPolicy_Exception() throws Exception { + when(toscaServiceTemplateService.fetchLatestPolicies(WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, + WRONG_POLICY_EVERYTHING, null)) + .thenThrow(new PfModelException(Response.Status.BAD_REQUEST, "Error")); + var fetchPoliciesExcReq = get("/policytypes/wrong/versions/wrong/policies/wrong/versions/latest"); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isBadRequest()); + } + + @Test + void createPolicy() throws Exception { + var toscaTemplate = new ToscaServiceTemplate(); + toscaTemplate.setName(SOME_POLICY_NAME); + toscaTemplate.setVersion(SOME_POLICY_VERSION); + when(toscaServiceTemplateService.createPolicy(any())).thenReturn(toscaTemplate); + + var body = ResourceUtils.getResourceAsString("policies/vFirewall.policy.monitoring.input.tosca.v2.yaml"); + var postRequest = post(URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES) + .content(body).contentType("application/yaml"); + this.mvc.perform(postRequest).andExpect(status().isCreated()); + + // exception scenario + given(toscaServiceTemplateService.createPolicy(any())).willThrow(pfException); + var postExceptionReq = post("/policytypes/wrong/versions/wrong/policies") + .content(body).contentType("application/yaml"); + this.mvc.perform(postExceptionReq).andExpect(status().isBadRequest()); + } + + @Test + void deleteSpecificVersionOfPolicy() throws Exception { + when(toscaServiceTemplateService.deletePolicy(SOME_POLICY_NAME, SOME_POLICY_VERSION)) + .thenReturn(new ToscaServiceTemplate()); + var deleteRequest = delete(URI_VALID_POLICY_TYPE_AND_VERSION_FOR_POLICIES + + "/somePolicyName/versions/somePolicyVersion") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(deleteRequest).andExpect(status().isOk()); + } + + @Test + void deleteSpecificVersionOfPolicy_Exception() throws Exception { + given(toscaServiceTemplateService.deletePolicy(WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING)) + .willThrow(pfException); + var deleteExceptionReq = delete("/policytypes/wrong/versions/wrong/policies/wrong/versions/wrong") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(deleteExceptionReq).andExpect(status().isBadRequest()); + } + + @Test + void getPolicies() throws Exception { + when(toscaServiceTemplateService.fetchPolicies(null, null, null, null, PolicyFetchMode.BARE)) + .thenReturn(new ToscaServiceTemplate()); + var fetchPoliciesReq = get("/policies").accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesReq).andExpect(status().isOk()); + + when(toscaServiceTemplateService.fetchPolicies( + null, null, null, null, PolicyFetchMode.REFERENCED)) + .thenThrow(new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Random error message")); + var fetchPoliciesExcReq = get("/policies?mode=REFERENCED") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isBadRequest()); + } + + @Test + void getPolicies_404Exception() throws Exception { + given(toscaServiceTemplateService.fetchPolicies( + null, null, null, null, PolicyFetchMode.REFERENCED)) + .willThrow(new PfModelRuntimeException(Response.Status.NOT_FOUND, "Random error message")); + var fetchPoliciesExcReq = get("/policies?mode=REFERENCED") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isNotFound()).andExpect(content() + .string("{\"code\":\"NOT_FOUND\",\"error\":\"No policies found\",\"details\":[\"No policies found\"]}")); + } + + @Test + void getSpecificPolicy() throws Exception { + when(toscaServiceTemplateService.fetchPolicies(null, null, + SOME_POLICY_NAME, SOME_POLICY_VERSION, PolicyFetchMode.BARE)) + .thenReturn(new ToscaServiceTemplate()); + var fetchPoliciesReq = get("/policies/somePolicyName/versions/somePolicyVersion") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesReq).andExpect(status().isOk()); + + given(toscaServiceTemplateService.fetchPolicies(null, null, + WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING, PolicyFetchMode.REFERENCED)) + .willThrow(new PfModelRuntimeException(Response.Status.NOT_FOUND, "Random error message")); + var fetchPoliciesExcReq = get("/policies/wrong/versions/wrong?mode=REFERENCED") + .accept(MediaType.APPLICATION_JSON); + this.mvc.perform(fetchPoliciesExcReq).andExpect(status().isNotFound()); + } + + @Test + void createPolicies() throws Exception { + var toscaTemplate = new ToscaServiceTemplate(); + toscaTemplate.setName(SOME_POLICY_NAME); + toscaTemplate.setVersion(SOME_POLICY_VERSION); + when(toscaServiceTemplateService.createPolicies(any())).thenReturn(toscaTemplate); + + var body = ResourceUtils.getResourceAsString("policies/vFirewall.policy.monitoring.input.tosca.v2.yaml"); + var postRequest = post("/policies").content(body).contentType("application/yaml"); + this.mvc.perform(postRequest).andExpect(status().isCreated()); + + // exception scenario + given(toscaServiceTemplateService.createPolicies(any())).willThrow(pfException); + var postExceptionReq = post("/policies").content(body).contentType("application/yaml"); + this.mvc.perform(postExceptionReq).andExpect(status().isBadRequest()); + } + + @Test + void deleteSpecificPolicy() throws Exception { + when(toscaServiceTemplateService.deletePolicy(SOME_POLICY_NAME, SOME_POLICY_VERSION)) + .thenReturn(new ToscaServiceTemplate()); + var deleteRequest = delete("/policies/somePolicyName/versions/somePolicyVersion"); + this.mvc.perform(deleteRequest).andExpect(status().isOk()); + + given(toscaServiceTemplateService.deletePolicy(WRONG_POLICY_EVERYTHING, WRONG_POLICY_EVERYTHING)) + .willThrow(pfException); + var deleteExcReq = delete("/policies/wrong/versions/wrong"); + this.mvc.perform(deleteExcReq).andExpect(status().isBadRequest()); + } +}
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java deleted file mode 100644 index 5896b352..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java +++ /dev/null @@ -1,700 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. - * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2020, 2022-2023 Nordix Foundation. - * Modifications Copyright (C) 2020-2023 Bell Canada. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.api.main.rest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import jakarta.ws.rs.client.Invocation; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.Response.Status; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.onap.policy.api.main.PolicyApiApplication; -import org.onap.policy.api.main.rest.utils.CommonTestRestController; -import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.common.utils.resources.TextFileUtils; -import org.onap.policy.common.utils.security.SelfSignedKeyStore; -import org.onap.policy.models.errors.concepts.ErrorResponse; -import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; - -/** - * Class to perform unit test of {@link ApiRestController}. - * - * @author Chenfei Gao (cgao@research.att.com) - */ -@SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles({ "test", "default" }) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) -class TestApiRestServer extends CommonTestRestController { - - private static final String ALIVE = "alive"; - private static final String SELF = NetworkUtil.getHostname(); - private static final String NAME = "Policy API"; - private static final String APP_JSON = "application/json"; - private static final String APP_YAML = "application/yaml"; - - private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; - - private static final String OP_POLICY_NAME_VCPE = "operational.restart"; - - private static final String POLICYTYPES = "policytypes"; - private static final String POLICYTYPES_TCA = "policytypes/onap.policies.monitoring.tcagen2"; - private static final String POLICYTYPES_COLLECTOR = - "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server"; - private static final String POLICYTYPES_TCA_VERSION = "policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0"; - private static final String POLICYTYPES_TCA_LATEST = "policytypes/onap.policies.monitoring.tcagen2/versions/latest"; - private static final String POLICYTYPES_COLLECTOR_VERSION = - "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/1.0.0"; - private static final String POLICYTYPES_COLLECTOR_LATEST = - "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/latest"; - - private static final String POLICYTYPES_DROOLS = "policytypes/onap.policies.controlloop.operational.common.Drools"; - private static final String POLICYTYPES_DROOLS_VERSION = POLICYTYPES_DROOLS + "/versions/1.0.0"; - private static final String POLICYTYPES_DROOLS_VERSION_LATEST = POLICYTYPES_DROOLS + "/versions/latest"; - - private static final String POLICYTYPES_NAMING_VERSION = POLICYTYPES + "/onap.policies.Naming/versions/1.0.0"; - - private static final String POLICYTYPES_TCA_POLICIES = - "policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0/policies"; - private static final String POLICYTYPES_TCA_POLICIES_VCPE = - "policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca"; - private static final String POLICYTYPES_TCA_POLICIES_VCPE_VERSION1 = - "policytypes/" + "onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca/versions/1.0.0"; - private static final String POLICYTYPES_TCA_POLICIES_VCPE_LATEST = "policytypes/" - + "onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca/versions/latest"; - - private static final String POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION = - POLICYTYPES_DROOLS_VERSION + "/policies/" + OP_POLICY_NAME_VCPE + "/versions/1.0.0"; - - private static final String POLICIES = "policies"; - - private static final String TOSCA_POLICY_VER_RESOURCE = - "policytypes/onap.restart.tca.snapshot.yaml"; - // @formatter:off - - private static final String[] TOSCA_POLICY_RESOURCE_NAMES = {"policies/vCPE.policy.monitoring.input.tosca.json", - "policies/vCPE.policy.monitoring.input.tosca.yaml", "policies/vDNS.policy.monitoring.input.tosca.json", - "policies/vDNS.policy.monitoring.input.tosca.v2.yaml"}; - - private static final String[] TOSCA_POLICIES_RESOURCE_NAMES = { - "policies/vCPE.policies.optimization.input.tosca.json", "policies/vCPE.policies.optimization.input.tosca.yaml"}; - - private static final String TOSCA_POLICYTYPE_OP_RESOURCE = - "policytypes/onap.policies.controlloop.operational.Common.yaml"; - - private static final String TOSCA_POLICYTYPE_VER_RESOURCE = - "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.snapshot.yaml"; - - private static final String[] TOSCA_POLICYTYPE_RESOURCE_NAMES = { - "policytypes/onap.policies.monitoring.tcagen2.yaml", - "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml", - "policytypes/onap.policies.controlloop.operational.common.Drools.yaml", - "policytypes/onap.policies.controlloop.guard.Common.yaml", - "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml", - "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml", - "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml", - "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml", - "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml", - "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml", - "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml", - "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml", - "policytypes/onap.policies.optimization.resource.PciPolicy.yaml", - "policytypes/onap.policies.optimization.service.QueryPolicy.yaml", - "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml", - "policytypes/onap.policies.optimization.resource.Vim_fit.yaml", - "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml"}; - - private static final String TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON = - "policies/vCPE.policy.operational.input.tosca.json"; - - private static final String TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML = - "policies/vCPE.policy.operational.input.tosca.yaml"; - - private static final String POLICIES_VCPE_VERSION1 = "policies/onap.restart.tca/versions/1.0.0"; - // @formatter:on - - private static final StandardCoder standardCoder = new StandardCoder(); - private static SelfSignedKeyStore keystore; - - @LocalServerPort - private int apiPort; - - /** - * Initializes parameters and set up test environment. - * - * @throws IOException on I/O exceptions - * @throws InterruptedException if interrupted - */ - @BeforeAll - static void setupParameters() throws IOException, InterruptedException { - keystore = new SelfSignedKeyStore(); - } - - @DynamicPropertySource - static void registerPgProperties(DynamicPropertyRegistry registry) { - registry.add("server.ssl.enabled", () -> "true"); - registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); - registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); - registry.add("server.ssl.key-store-type", () -> "PKCS12"); - registry.add("server.ssl.key-alias", () -> "policy@policy.onap.org"); - registry.add("server.ssl.key-password", () -> SelfSignedKeyStore.PRIVATE_KEY_PASSWORD); - } - - @Test - void testSwagger() throws Exception { - super.testSwagger(apiPort); - } - - @Test - void testCreatePolicyTypes() throws Exception { - for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(response); - assertFalse(response.getPolicyTypes().isEmpty()); - } - - // Send a policy type with a null value to trigger an error - Response rawResponse = readResource(POLICYTYPES, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - String firstPolicyType = response.getPolicyTypes().keySet().iterator().next(); - response.getPolicyTypes().put(firstPolicyType, null); - Response rawResponse2 = createResource(POLICYTYPES, standardCoder.encode(response), apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse2.getStatus()); - ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class); - assertEquals("no policy types specified on service template", errorResponse.getErrorMessage()); - } - - @Test - void testCreatePolicies() throws Exception { - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit(); - - // Send a policy with no policy type trigger an error - String toscaPolicy = ResourceUtils - .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]); - - toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.tcagen2", "IDontExist"); - TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml"); - - Response rawResponse2 = - createResource(POLICYTYPES_TCA_POLICIES, - "src/test/resources/policies/BadTestPolicy.yaml", apiPort); - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse2.getStatus()); - ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class); - assertThat(errorResponse.getErrorMessage()) - .contains("item \"entity\" value \"onap.restart.tca:1.0.0\" INVALID, does not equal existing entity"); - } - - @Test - void testSimpleCreatePolicies() throws Exception { - for (String resrcName : TOSCA_POLICIES_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICIES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit(); - - // Send a policy with no policy type trigger an error - String toscaPolicy = ResourceUtils - .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]); - - toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.tcagen2", "IDontExist"); - toscaPolicy = toscaPolicy.replaceAll("onap.restart.tca", "onap.restart.tca.IDontExist"); - TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml"); - - Response rawResponse2 = - createResource(POLICIES, "src/test/resources/policies/BadTestPolicy.yaml", apiPort); - ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class); - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse2.getStatus()); - assertThat(errorResponse.getErrorMessage()) - .contains("item \"policy type\" value \"IDontExist:1.0.0\" INVALID, not found"); - } - - @Test - void testPoliciesVersioning() throws Exception { - var rawResponse = createResource(POLICYTYPES, TOSCA_POLICYTYPE_VER_RESOURCE, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = createResource(POLICIES, TOSCA_POLICY_VER_RESOURCE, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - @SuppressWarnings("unchecked") - @Test - void testToscaCompliantOpDroolsPolicies() throws Exception { - Response rawResponse = createResource(POLICYTYPES, TOSCA_POLICYTYPE_OP_RESOURCE, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_YAML, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - ToscaServiceTemplate toscaVcpeSt = rawResponse.readEntity(ToscaServiceTemplate.class); - assertEquals(1, toscaVcpeSt.getToscaTopologyTemplate().getPolicies().size()); - assertEquals(OP_POLICY_NAME_VCPE, - toscaVcpeSt.getToscaTopologyTemplate().getPolicies().get(0).get(OP_POLICY_NAME_VCPE).getName()); - - Map<String, Object> props = - toscaVcpeSt.getToscaTopologyTemplate().getPolicies().get(0).get(OP_POLICY_NAME_VCPE).getProperties(); - assertNotNull(props); - - List<Object> operations = (List<Object>) props.get("operations"); - assertEquals(1, operations.size()); - assertEquals(props.get("trigger"), ((Map<String, Object>) operations.get(0)).get("id")); - - Map<String, Object> operation = - (Map<String, Object>) ((Map<String, Object>) operations.get(0)).get("operation"); - assertEquals("APPC", operation.get("actor")); - assertEquals("Restart", operation.get("operation")); - - rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - @Test - void testHealthCheckSuccessJson() throws Exception { - testHealthCheckSuccess(APP_JSON); - } - - @Test - void testHealthCheckSuccessYaml() throws Exception { - testHealthCheckSuccess(APP_YAML); - } - - private void testHealthCheckSuccess(String mediaType) throws Exception { - final Invocation.Builder invocationBuilder = sendHttpsRequest( - HEALTHCHECK_ENDPOINT, mediaType, apiPort); - final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); - validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); - } - - @Test - void testReadPolicyTypesJson() throws Exception { - testReadPolicyTypes(APP_JSON); - } - - @Test - void testReadPolicyTypesYaml() throws Exception { - testReadPolicyTypes(APP_YAML); - } - - private void testReadPolicyTypes(String mediaType) throws Exception { - Response rawResponse = - readResource("policytypes/onap.policies.optimization.resource.HpaPolicy", mediaType, - apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(namingServiceTemplate); - assertEquals(3, namingServiceTemplate.getPolicyTypesAsMap().size()); - assertEquals(5, namingServiceTemplate.getDataTypesAsMap().size()); - - rawResponse = readResource(POLICYTYPES, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertFalse(response.getPolicyTypes().isEmpty()); - - rawResponse = readResource(POLICYTYPES_TCA, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_TCA_VERSION, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_TCA_LATEST, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_COLLECTOR, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_COLLECTOR_VERSION, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_COLLECTOR_LATEST, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_DROOLS_VERSION_LATEST, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_NAMING_VERSION, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - @Test - void testDeletePolicyTypeJson() throws Exception { - testDeletePolicyType(APP_JSON); - } - - @Test - void testDeletePolicyTypeYaml() throws Exception { - testDeletePolicyType(APP_YAML); - } - - private void testDeletePolicyType(String mediaType) throws Exception { - Response rawResponse = deleteResource("policytypes/onap.policies.IDoNotExist/versions/1.0.0", - mediaType, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - - rawResponse = createResource(POLICYTYPES, "policytypes/onap.policies.Test.yaml", apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = - readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = - deleteResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = - readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - } - - @Test - void testReadPoliciesJson() throws Exception { - testReadPolicies(APP_JSON); - } - - @Test - void testReadPoliciesYaml() throws Exception { - testReadPolicies(APP_YAML); - } - - private void testReadPolicies(String mediaType) throws Exception { - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - } - - @Test - void testNamingPolicyGet() throws Exception { - - Response rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0?mode=referenced", APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - ToscaServiceTemplate namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size()); - assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size()); - assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size()); - - rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest?mode=referenced", APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size()); - assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size()); - assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size()); - - rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies" - + "?mode=referenced", APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size()); - assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size()); - assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size()); - - rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - - assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size()); - assertNull(namingServiceTemplate.getPolicyTypes()); - assertNull(namingServiceTemplate.getDataTypes()); - - rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/" - + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest", APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size()); - assertNull(namingServiceTemplate.getPolicyTypes()); - assertNull(namingServiceTemplate.getDataTypes()); - - rawResponse = - readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies", APP_JSON, - apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class); - assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size()); - assertNull(namingServiceTemplate.getPolicyTypes()); - assertNull(namingServiceTemplate.getDataTypes()); - } - - @Test - void testDeletePoliciesJson() throws Exception { - testDeletePolicies(APP_JSON); - } - - @Test - void testDeletePoliciesYaml() throws Exception { - testDeletePolicies(APP_YAML); - } - - private void testDeletePolicies(String mediaType) throws Exception { - Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - ErrorResponse error = rawResponse.readEntity(ErrorResponse.class); - assertEquals("policy onap.restart.tca:1.0.0 not found", error.getErrorMessage()); - } - - @Test - void testDeletePolicyVersionJson() throws Exception { - testDeletePolicyVersion(APP_JSON); - } - - @Test - void testDeletePolicyVersionYaml() throws Exception { - testDeletePolicyVersion(APP_YAML); - } - - private void testDeletePolicyVersion(String mediaType) throws Exception { - for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(response); - assertFalse(response.getPolicyTypes().isEmpty()); - } - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class); - assertEquals("policies for onap.restart.tca:1.0.0 do not exist", errorResponse.getErrorMessage()); - - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - errorResponse = rawResponse.readEntity(ErrorResponse.class); - assertEquals("policies for onap.restart.tca:null do not exist", errorResponse.getErrorMessage()); - - rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - errorResponse = rawResponse.readEntity(ErrorResponse.class); - assertEquals("policies for onap.restart.tca:null do not exist", errorResponse.getErrorMessage()); - } - - @Test - void testGetAllVersionOfPolicyJson() throws Exception { - testGetAllVersionOfPolicy(APP_JSON); - } - - @Test - void testGetAllVersionOfPolicyYaml() throws Exception { - testGetAllVersionOfPolicy(APP_YAML); - } - - private void testGetAllVersionOfPolicy(String mediaType) throws Exception { - for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(response); - assertFalse(response.getPolicyTypes().isEmpty()); - } - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - } - - @Test - void testGetPoliciesJson() throws Exception { - getPolicies(APP_JSON); - } - - @Test - void testGetPoliciesYaml() throws Exception { - getPolicies(APP_YAML); - } - - private void getPolicies(String mediaType) throws Exception { - for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertThat(response).isNotNull(); - assertThat(response.getPolicyTypes()).isNotEmpty(); - } - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - } - Response rawResponse = readResource(POLICIES, mediaType, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertThat(response.getToscaTopologyTemplate().getPolicies()).isNotEmpty(); - } - - @Test - void testGetSpecificPolicyJson() throws Exception { - getSpecificPolicy(APP_JSON); - } - - @Test - void testGetSpecificPolicyYaml() throws Exception { - getSpecificPolicy(APP_YAML); - } - - private void getSpecificPolicy(String mediaType) throws Exception { - for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES, resrcName, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertThat(response).isNotNull(); - assertThat(response.getPolicyTypes()).isNotEmpty(); - } - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - } - Response rawResponse = readResource(POLICIES_VCPE_VERSION1, mediaType, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertThat(response.getToscaTopologyTemplate().getPolicies()).hasSize(1); - } - - @Test - void testDeleteSpecificPolicy() throws Exception { - Response rawResponse; - for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { - rawResponse = createResource(POLICYTYPES, resrcName, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertThat(response).isNotNull(); - assertThat(response.getPolicyTypes()).isNotEmpty(); - } - for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) { - rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - } - - rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - - // delete a particular policy - rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); - - rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Status.NOT_FOUND.getStatusCode()); - - rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON, apiPort); - assertThat(rawResponse.getStatus()).isEqualTo(Status.NOT_FOUND.getStatusCode()); - - } - - private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code, - final String message, final HealthCheckReport report) { - - assertEquals(name, report.getName()); - assertEquals(url, report.getUrl()); - assertEquals(healthy, report.isHealthy()); - assertEquals(code, report.getCode()); - assertEquals(message, report.getMessage()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java b/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java index bf1d49be..ce772f67 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java @@ -3,7 +3,7 @@ * ONAP Policy API * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019, 2023 Nordix Foundation. + * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,10 +24,17 @@ package org.onap.policy.api.main.rest; +import java.lang.reflect.Field; import java.util.UUID; +import java.util.concurrent.Semaphore; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.onap.policy.api.main.exception.PolicyApiRuntimeException; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; import org.springframework.http.ResponseEntity; +import org.springframework.test.util.ReflectionTestUtils; /** * Class to perform unit testing of CommonRestController. @@ -46,7 +53,27 @@ class TestCommonRestController { * Tests null response for null object */ @Test - void testToJsonNull() { + void testToJsonNull() throws CoderException { Assertions.assertNull(crc.toJson(null)); + + var mockCoder = Mockito.mock(StandardCoder.class); + Mockito.when(mockCoder.encode("fail")).thenThrow(new CoderException("fail")); + ReflectionTestUtils.setField(crc, "coder", mockCoder); + Assertions.assertNull(crc.toJson("fail")); + } + + @Test + void testLock() throws Exception { + Class<?> mockControllerClass = Class.forName("org.onap.policy.api.main.rest.CommonRestController"); + CommonRestController mockController = + (CommonRestController) mockControllerClass.getDeclaredConstructor().newInstance(); + var mockSemaphore = Mockito.mock(Semaphore.class); + Mockito.doThrow(new InterruptedException("runtime error")).when(mockSemaphore).acquire(); + Field field = mockControllerClass.getDeclaredField("mutex"); + field.setAccessible(true); + field.set(mockController, mockSemaphore); + + Assertions.assertThrows(PolicyApiRuntimeException.class, mockController::lock); + ReflectionTestUtils.setField(crc, "mutex", new Semaphore(1)); } }
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java b/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java index 8dd0d731..22c4346d 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy API * ================================================================================ - * Copyright (C) 2022-2023 Nordix Foundation. All rights reserved. + * Copyright (C) 2022-2024 Nordix Foundation. 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. @@ -22,197 +22,149 @@ package org.onap.policy.api.main.rest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import jakarta.ws.rs.core.GenericType; import jakarta.ws.rs.core.Response; -import java.io.IOException; import java.util.List; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.onap.policy.api.main.PolicyApiApplication; -import org.onap.policy.api.main.rest.utils.CommonTestRestController; +import org.mockito.MockitoAnnotations; import org.onap.policy.api.main.service.ToscaServiceTemplateService; -import org.onap.policy.common.utils.security.SelfSignedKeyStore; -import org.onap.policy.models.errors.concepts.ErrorResponse; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; -/** - * Class to perform unit test of {@link NodeTemplateController}. - * - */ -@SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles({ "test", "default" }) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -public class TestNodeTemplateController extends CommonTestRestController { - - private static final String TOSCA_NODE_TEMPLATE_RESOURCE = - "nodetemplates/nodetemplates.metadatasets.input.tosca.json"; - private static final String TOSCA_INVALID_NODE_TYPE = - "nodetemplates/nodetemplates.metadatasets.invalid.nodetype.json"; - private static final String TOSCA_INVALID_TEMPLATE = - "nodetemplates/nodetemplates.metadatasets.no.nodetemplate.json"; - private static final String TOSCA_UPDATE_NODE_TEMPLATES = "nodetemplates/nodetemplates.metadatasets.update.json"; +@WebMvcTest(controllers = NodeTemplateController.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) +@ActiveProfiles({"default", "test-mvc"}) +class TestNodeTemplateController { - private static final String NODE_TEMPLATES = "nodetemplates"; - private static final String SPECIFIC_NODE_TEMPLATE = "nodetemplates/apexMetadata_adaptive/versions/1.0.0"; - private static final String INVALID_NODE_TEMPLATE_ID = "nodetemplates/invalid_template/versions/1.0.0"; + @Autowired + private MockMvc mvc; - private static final List<String> nodeTemplateKeys = - List.of("apexMetadata_grpc", "apexMetadata_adaptive", "apexMetadata_decisionMaker"); + @MockBean + private ToscaServiceTemplateService toscaServiceTemplateService; - protected static final String APP_JSON = "application/json"; + AutoCloseable autoCloseable; - private static SelfSignedKeyStore keystore; + private static final PfModelException PF_MODEL_EXCEPTION = + new PfModelException(Response.Status.BAD_REQUEST, "Error"); - @LocalServerPort - private int apiPort; + @BeforeEach + void setUp(@Autowired WebApplicationContext context) { + autoCloseable = MockitoAnnotations.openMocks(this); + mvc = MockMvcBuilders.webAppContextSetup(context).build(); + } - @Autowired - private ToscaServiceTemplateService toscaServiceTemplateService; + @AfterEach + void tearDown() throws Exception { + autoCloseable.close(); + } - /** - * Initializes parameters and set up test environment. - * - * @throws IOException on I/O exceptions - * @throws InterruptedException if interrupted - */ - @BeforeAll - public static void setupParameters() throws IOException, InterruptedException { - keystore = new SelfSignedKeyStore(); + @Test + void createToscaNodeTemplates() throws Exception { + var body = ResourceUtils.getResourceAsString("nodetemplates/nodetemplates.metadatasets.input.tosca.json"); + var createRequest = post("/nodetemplates").contentType(MediaType.APPLICATION_JSON).content(body); + when(toscaServiceTemplateService.createToscaNodeTemplates(any(ToscaServiceTemplate.class))) + .thenReturn(new ToscaServiceTemplate()); + mvc.perform(createRequest).andExpect(status().isCreated()); } - /** - * Clean up the database. - * - */ - @AfterEach - public void clearDb() { - for (String name : nodeTemplateKeys) { - try { - toscaServiceTemplateService.deleteToscaNodeTemplate(name, "1.0.0"); - } catch (Exception e) { - //do nothing - } - } + @Test + void createToscaNodeTemplates_Exception() throws Exception { + var body = ResourceUtils.getResourceAsString("nodetemplates/nodetemplates.metadatasets.input.tosca.json"); + var createRequest = post("/nodetemplates").contentType(MediaType.APPLICATION_JSON).content(body); + when(toscaServiceTemplateService.createToscaNodeTemplates(any(ToscaServiceTemplate.class))) + .thenThrow(PF_MODEL_EXCEPTION); + mvc.perform(createRequest).andExpect(status().isBadRequest()); } - @DynamicPropertySource - static void registerPgProperties(DynamicPropertyRegistry registry) { - registry.add("server.ssl.enabled", () -> "true"); - registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); - registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); - registry.add("server.ssl.key-store-type", () -> "PKCS12"); - registry.add("server.ssl.key-alias", () -> "policy@policy.onap.org"); - registry.add("server.ssl.key-password", () -> SelfSignedKeyStore.PRIVATE_KEY_PASSWORD); + @Test + void updateToscaNodeTemplates() throws Exception { + var body = ResourceUtils.getResourceAsString("nodetemplates/nodetemplates.metadatasets.input.tosca.json"); + var updateRequest = put("/nodetemplates").contentType(MediaType.APPLICATION_JSON).content(body); + when(toscaServiceTemplateService.updateToscaNodeTemplates(any(ToscaServiceTemplate.class))) + .thenReturn(new ToscaServiceTemplate()); + mvc.perform(updateRequest).andExpect(status().isOk()); } + @Test + void updateToscaNodeTemplates_Exception() throws Exception { + var body = ResourceUtils.getResourceAsString("nodetemplates/nodetemplates.metadatasets.input.tosca.json"); + var updateRequest = put("/nodetemplates").contentType(MediaType.APPLICATION_JSON).content(body); + when(toscaServiceTemplateService.updateToscaNodeTemplates(any(ToscaServiceTemplate.class))) + .thenThrow(PF_MODEL_EXCEPTION); + mvc.perform(updateRequest).andExpect(status().isBadRequest()); + } @Test - void testCreateToscaNodeTemplates() throws Exception { - Response rawResponse = createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(response); - assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); - - // Send a node type with a invalid value to trigger an error - rawResponse = createResource(NODE_TEMPLATES, TOSCA_INVALID_NODE_TYPE, apiPort); - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse.getStatus()); - ErrorResponse response2 = rawResponse.readEntity(ErrorResponse.class); - assertThat(response2.getErrorMessage()) - .containsPattern("^NODE_TYPE .* for toscaNodeTemplate .* does not exist$"); - - // Send invalid tosca template with no node templates - rawResponse = createResource(NODE_TEMPLATES, TOSCA_INVALID_TEMPLATE, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - response2 = rawResponse.readEntity(ErrorResponse.class); - assertEquals("node templates not present on the service template", response2.getErrorMessage()); + void deleteToscaNodeTemplates() throws Exception { + var deleteRequest = delete("/nodetemplates/nodeName/versions/nodeVersion") + .accept(MediaType.APPLICATION_JSON); + when(toscaServiceTemplateService.deleteToscaNodeTemplate("nodeName", "nodeVersion")) + .thenReturn(new ToscaServiceTemplate()); + mvc.perform(deleteRequest).andExpect(status().isOk()); } + @Test + void deleteToscaNodeTemplates_Exception() throws Exception { + var deleteRequest = delete("/nodetemplates/nodeName/versions/nodeVersion") + .accept(MediaType.APPLICATION_JSON); + when(toscaServiceTemplateService.deleteToscaNodeTemplate("nodeName", "nodeVersion")) + .thenThrow(PF_MODEL_EXCEPTION); + mvc.perform(deleteRequest).andExpect(status().isBadRequest()); + } @Test - void testReadNodeTemplates() throws Exception { - Response rawResponse = readResource(NODE_TEMPLATES, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - List<?> nodeTemplates = rawResponse.readEntity(List.class); - assertNotNull(nodeTemplates); - assertEquals(0, nodeTemplates.size()); - - createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); - rawResponse = readResource(NODE_TEMPLATES, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - nodeTemplates = rawResponse.readEntity(List.class); - assertNotNull(nodeTemplates); - assertEquals(3, nodeTemplates.size()); - - rawResponse = readResource(SPECIFIC_NODE_TEMPLATE, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - List<ToscaNodeTemplate> retrievedTemplate = - rawResponse.readEntity(new GenericType<List<ToscaNodeTemplate>>() {}); - assertNotNull(nodeTemplates); - assertEquals(1, retrievedTemplate.size()); - String retrievedTemplateName = retrievedTemplate.get(0).getName(); - assertEquals("apexMetadata_adaptive", retrievedTemplateName); + void getSpecificVersionOfNodeTemplate() throws Exception { + var getRequest = get("/nodetemplates/nodeName/versions/nodeVersion") + .accept(MediaType.APPLICATION_JSON); + when(toscaServiceTemplateService.fetchToscaNodeTemplates("nodeName", "nodeVersion")) + .thenReturn(List.of(new ToscaNodeTemplate())); + mvc.perform(getRequest).andExpect(status().isOk()); } @Test - void testUpdateNodeTemplates() throws Exception { - createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); - Response rawResponse = updateResource(NODE_TEMPLATES, TOSCA_UPDATE_NODE_TEMPLATES, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(response); - assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); - String updatedValue = "" + response.getToscaTopologyTemplate().getNodeTemplates().get("apexMetadata_grpc") - .getMetadata().get("state"); - assertEquals("passive", updatedValue); - - rawResponse = updateResource(NODE_TEMPLATES, TOSCA_INVALID_NODE_TYPE, APP_JSON, apiPort); - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse.getStatus()); - ErrorResponse response2 = rawResponse.readEntity(ErrorResponse.class); - assertThat(response2.getErrorMessage()) - .containsPattern("^NODE_TYPE .* for toscaNodeTemplate .* does not exist$"); - - // Send invalid tosca template with no node templates - rawResponse = updateResource(NODE_TEMPLATES, TOSCA_INVALID_TEMPLATE, APP_JSON, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - ErrorResponse response3 = rawResponse.readEntity(ErrorResponse.class); - assertEquals("node templates not present on the service template", response3.getErrorMessage()); + void getSpecificVersionOfNodeTemplate_Exception() throws Exception { + var getRequest = get("/nodetemplates/nodeName/versions/nodeVersion") + .accept(MediaType.APPLICATION_JSON); + when(toscaServiceTemplateService.fetchToscaNodeTemplates("nodeName", "nodeVersion")) + .thenThrow(PF_MODEL_EXCEPTION); + mvc.perform(getRequest).andExpect(status().isBadRequest()); } @Test - void testDeleteNodeTemplates() throws Exception { - createResource(NODE_TEMPLATES, TOSCA_NODE_TEMPLATE_RESOURCE, apiPort); - Response rawResponse = deleteResource(SPECIFIC_NODE_TEMPLATE, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class); - assertNotNull(response); - assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); - - rawResponse = readResource(NODE_TEMPLATES, APP_JSON, apiPort); - assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus()); - List<?> nodeTemplates = rawResponse.readEntity(List.class); - assertNotNull(nodeTemplates); - assertEquals(2, nodeTemplates.size()); - - // Send invalid id - rawResponse = deleteResource(INVALID_NODE_TEMPLATE_ID, APP_JSON, apiPort); - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus()); - ErrorResponse response3 = rawResponse.readEntity(ErrorResponse.class); - assertThat(response3.getErrorMessage()).containsPattern("^node template .* not found$"); + void getAllNodeTemplates() throws Exception { + var getRequest = get("/nodetemplates") + .accept(MediaType.APPLICATION_JSON); + when(toscaServiceTemplateService.fetchToscaNodeTemplates(null, null)) + .thenReturn(List.of(new ToscaNodeTemplate())); + mvc.perform(getRequest).andExpect(status().isOk()); } -} + @Test + void getAllNodeTemplates_Exception() throws Exception { + var getRequest = get("/nodetemplates") + .accept(MediaType.APPLICATION_JSON); + when(toscaServiceTemplateService.fetchToscaNodeTemplates(null, null)) + .thenThrow(PF_MODEL_EXCEPTION); + mvc.perform(getRequest).andExpect(status().isBadRequest()); + } +}
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/e2e/TestApiRestControllerE2E.java b/main/src/test/java/org/onap/policy/api/main/rest/e2e/TestApiRestControllerE2E.java new file mode 100644 index 00000000..9af8c3dc --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/e2e/TestApiRestControllerE2E.java @@ -0,0 +1,449 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest.e2e; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.File; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.coder.StandardYamlCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.client.ExchangeFilterFunctions; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +@ActiveProfiles({"default", "test"}) +@AutoConfigureWebTestClient +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestApiRestControllerE2E { + + @Autowired + WebTestClient webClient; + + protected static final MediaType APPLICATION_YAML = new MediaType("application", "yaml"); + protected static final MediaType APPLICATION_JSON = new MediaType("application", "json"); + protected static final String OP_POLICY_NAME_VCPE = "operational.restart"; + + protected static final String[] TOSCA_POLICYTYPE_RESOURCE_NAMES = { + "policytypes/onap.policies.monitoring.tcagen2.yaml", + "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml", + "policytypes/onap.policies.controlloop.operational.common.Drools.yaml", + "policytypes/onap.policies.controlloop.guard.Common.yaml", + "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml", + "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml", + "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml", + "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml", + "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml", + "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml", + "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml", + "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml", + "policytypes/onap.policies.optimization.resource.PciPolicy.yaml", + "policytypes/onap.policies.optimization.service.QueryPolicy.yaml", + "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml", + "policytypes/onap.policies.optimization.resource.Vim_fit.yaml", + "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml"}; + protected static final String POLICYTYPES = "/policytypes"; + protected static final String POLICYTYPES_TCA = "/policytypes/onap.policies.monitoring.tcagen2"; + protected static final String POLICYTYPES_COLLECTOR = + "/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server"; + protected static final String POLICYTYPES_TCA_VERSION = + "/policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0"; + protected static final String POLICYTYPES_TCA_LATEST = + "/policytypes/onap.policies.monitoring.tcagen2/versions/latest"; + protected static final String POLICYTYPES_COLLECTOR_VERSION = + "/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/1.0.0"; + protected static final String POLICYTYPES_COLLECTOR_LATEST = + "/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/latest"; + + protected static final String POLICYTYPES_DROOLS = + "/policytypes/onap.policies.controlloop.operational.common.Drools"; + protected static final String POLICYTYPES_DROOLS_VERSION = POLICYTYPES_DROOLS + "/versions/1.0.0"; + protected static final String POLICYTYPES_DROOLS_VERSION_LATEST = POLICYTYPES_DROOLS + "/versions/latest"; + + protected static final String POLICYTYPES_NAMING_VERSION = POLICYTYPES + "/onap.policies.Naming/versions/1.0.0"; + + protected static final String POLICYTYPES_TCA_POLICIES = + "/policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0/policies"; + protected static final String POLICYTYPES_TCA_POLICIES_VCPE = + "/policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca"; + protected static final String POLICYTYPES_TCA_POLICIES_VCPE_VERSION1 = "/policytypes/" + + "onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca/versions/1.0.0"; + protected static final String POLICYTYPES_TCA_POLICIES_VCPE_LATEST = "/policytypes/" + + "onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca/versions/latest"; + + protected static final String POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION = + POLICYTYPES_DROOLS_VERSION + "/policies/" + OP_POLICY_NAME_VCPE + "/versions/1.0.0"; + + protected static final String POLICIES = "/policies"; + + protected static final String[] TOSCA_POLICY_RESOURCE_NAMES = { + "policies/vCPE.policy.monitoring.input.tosca.json", + "policies/vCPE.policy.monitoring.input.tosca.yaml", + "policies/vDNS.policy.monitoring.input.tosca.json", + "policies/vDNS.policy.monitoring.input.tosca.v2.yaml"}; + + protected static final String[] TOSCA_POLICIES_RESOURCE_NAMES = { + "policies/vCPE.policies.optimization.input.tosca.json", + "policies/vCPE.policies.optimization.input.tosca.yaml"}; + + private static final String TOSCA_POLICYTYPE_OP_RESOURCE = + "policytypes/onap.policies.controlloop.operational.Common.yaml"; + + protected static final String TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON = + "policies/vCPE.policy.operational.input.tosca.json"; + + protected static final String TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML = + "policies/vCPE.policy.operational.input.tosca.yaml"; + + protected static final String POLICIES_VCPE_VERSION1 = "/policies/onap.restart.tca/versions/1.0.0"; + + @BeforeEach + void beforeEach() { + var filter = ExchangeFilterFunctions.basicAuthentication("policyadmin", "zb!XztG34"); + webClient = webClient.mutate().filter(filter).build(); + } + + @Order(1) + @Test + void createPolicyType() { + for (String resourceName : TOSCA_POLICYTYPE_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, "/policytypes"); + } + } + + @Order(2) + @Test + void createPolicyWithPolicyTypeAndVersion() { + for (String resourceName : TOSCA_POLICY_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, POLICYTYPES_TCA_POLICIES); + } + + // try for bad policy + new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit(); + + // Send a policy with no policy type trigger an error + String toscaPolicy = ResourceUtils + .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]); + + toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.tcagen2", "IDontExist"); + + webClient.post().uri(POLICYTYPES_TCA_POLICIES).contentType(APPLICATION_YAML).bodyValue(toscaPolicy) + .exchange().expectStatus().is4xxClientError(); + } + + @Order(3) + @Test + void createPoliciesWithPolicyEndpoint() { + for (String resourceName : TOSCA_POLICIES_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, "/policies"); + } + } + + @Order(4) + @Test + void testPoliciesVersioning() { + var policyTypePath = "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.snapshot.yaml"; + performPostRequestIsCreated(policyTypePath, "/policytypes"); + + policyTypePath = "policytypes/onap.restart.tca.snapshot.yaml"; + performPostRequestIsCreated(policyTypePath, "/policies"); + } + + @Order(5) + @Test + void testToscaCompliantOpDroolsPolicies() { + performPostRequestIsCreated(TOSCA_POLICYTYPE_OP_RESOURCE, "/policytypes"); + + performGetRequest(POLICYTYPES_DROOLS_VERSION); + + performPostRequestIsCreated(TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON, POLICIES); + + performPostRequestIsCreated(TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML, POLICIES); + + performGetRequest(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION); + + performDeleteRequest(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION); + + performPostRequestIsCreated(TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML, POLICIES); + + performGetRequest(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION); + + var response = performGetRequestAndCollectResponse(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION); + assertEquals(1, response.getToscaTopologyTemplate().getPolicies().size()); + assertEquals(OP_POLICY_NAME_VCPE, + response.getToscaTopologyTemplate().getPolicies().get(0).get(OP_POLICY_NAME_VCPE).getName()); + Map<String, Object> props = response.getToscaTopologyTemplate().getPolicies() + .get(0).get(OP_POLICY_NAME_VCPE).getProperties(); + assertNotNull(props); + + if (props.get("operations") instanceof List<?> operations) { + assertEquals(1, operations.size()); + if (operations.get(0) instanceof Map<?, ?> operation) { + assertEquals(props.get("trigger"), operation.get("id")); + if (operation.get("operation") instanceof Map<?, ?> op) { + assertEquals("APPC", op.get("actor")); + assertEquals("Restart", op.get("operation")); + } + } + + } + + performDeleteRequest(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION); + } + + @Test + void getHealthCheck() { + webClient.get().uri("/healthcheck").accept(APPLICATION_JSON) + .exchange().expectStatus().isOk(); + } + + @Test + void getAllPolicyTypes() { + webClient.get().uri("/policytypes").accept(APPLICATION_JSON) + .exchange().expectStatus().isOk(); + } + + @Test + void getAllVersionsOfPolicyType() { + var uri = "/policytypes/onap.policies.optimization.resource.HpaPolicy"; + var response = performGetRequestAndCollectResponse(uri); + assertNotNull(response); + assertEquals(3, response.getPolicyTypesAsMap().size()); + assertEquals(5, response.getDataTypesAsMap().size()); + + performGetRequest(POLICYTYPES_TCA); + performGetRequest(POLICYTYPES_COLLECTOR); + performGetRequest(POLICYTYPES_DROOLS); + } + + @Test + void getSpecificVersionOfPolicyType() { + performGetRequest(POLICYTYPES_TCA_VERSION); + performGetRequest(POLICYTYPES_COLLECTOR_VERSION); + performGetRequest(POLICYTYPES_DROOLS_VERSION); + performGetRequest(POLICYTYPES_NAMING_VERSION); + } + + @Test + void getLatestVersionOfPolicyType() { + performGetRequest(POLICYTYPES_TCA_LATEST); + performGetRequest(POLICYTYPES_COLLECTOR_LATEST); + performGetRequest(POLICYTYPES_DROOLS_VERSION_LATEST); + + webClient.get().uri("/policytypes/wrong/versions/latest") + .accept(APPLICATION_JSON).exchange() + .expectStatus().isNotFound(); + } + + @Test + void deleteSpecificVersionOfPolicyType() { + performPostRequestIsCreated("policytypes/onap.policies.Test.yaml", POLICYTYPES); + var uri = "/policytypes/onap.policies.Test/versions/1.0.0"; + performGetRequest(uri); + performDeleteRequest("/policytypes/onap.policies.Test/versions/1.0.0"); + + // tried to delete again + webClient.delete().uri(uri).exchange().expectStatus().isNotFound(); + } + + @Test + void getPoliciesWithPolicyTypeAndVersionEndpoint() { + for (String resourceName : TOSCA_POLICY_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, POLICYTYPES_TCA_POLICIES); + } + + performGetRequest(POLICYTYPES_TCA_POLICIES); + performGetRequest(POLICYTYPES_TCA_POLICIES); + + performGetRequest(POLICYTYPES_TCA_POLICIES_VCPE); + performGetRequest(POLICYTYPES_TCA_POLICIES_VCPE); + + performGetRequest(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1); + performGetRequest(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1); + + performGetRequest(POLICYTYPES_TCA_POLICIES_VCPE_LATEST); + performGetRequest(POLICYTYPES_TCA_POLICIES_VCPE_LATEST); + } + + @Test + void getPoliciesWithPolicyTypeAndVersionEndpoint_CheckResponses() { + performGetRequestAndCollectResponse("/policytypes/onap.policies.Naming/versions/1.0.0/" + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0"); + + var response = performGetRequestAndCollectResponse( + "/policytypes/onap.policies.Naming/versions/1.0.0/" + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0?mode=referenced"); + + assertEquals(1, response.getToscaTopologyTemplate().getPoliciesAsMap().size()); + assertEquals(1, response.getPolicyTypesAsMap().size()); + assertEquals(3, response.getDataTypesAsMap().size()); + + response = performGetRequestAndCollectResponse( + "/policytypes/onap.policies.Naming/versions/1.0.0/" + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest?mode=referenced"); + assertEquals(1, response.getToscaTopologyTemplate().getPoliciesAsMap().size()); + assertEquals(1, response.getPolicyTypesAsMap().size()); + assertEquals(3, response.getDataTypesAsMap().size()); + + response = performGetRequestAndCollectResponse( + "/policytypes/onap.policies.Naming/versions/1.0.0/policies" + + "?mode=referenced"); + assertEquals(1, response.getToscaTopologyTemplate().getPoliciesAsMap().size()); + assertEquals(1, response.getPolicyTypesAsMap().size()); + assertEquals(3, response.getDataTypesAsMap().size()); + + response = performGetRequestAndCollectResponse( + "/policytypes/onap.policies.Naming/versions/1.0.0/" + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0"); + assertEquals(1, response.getToscaTopologyTemplate().getPoliciesAsMap().size()); + assertNull(response.getPolicyTypes()); + assertNull(response.getDataTypes()); + + response = performGetRequestAndCollectResponse( + "/policytypes/onap.policies.Naming/versions/1.0.0/" + + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest"); + assertEquals(1, response.getToscaTopologyTemplate().getPoliciesAsMap().size()); + assertNull(response.getPolicyTypes()); + assertNull(response.getDataTypes()); + + response = performGetRequestAndCollectResponse( + "/policytypes/onap.policies.Naming/versions" + + "/1.0.0/policies"); + assertEquals(1, response.getToscaTopologyTemplate().getPoliciesAsMap().size()); + assertNull(response.getPolicyTypes()); + assertNull(response.getDataTypes()); + } + + @Test + void deleteSpecificVersionOfPolicy() { + var policyTypeFile = "policytypes/onap.policies.monitoring.tcagen2.yaml"; + performPostRequestIsCreated(policyTypeFile, "/policytypes"); + + for (String resourceName : TOSCA_POLICY_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, POLICYTYPES_TCA_POLICIES); + } + + performDeleteRequest(POLICIES_VCPE_VERSION1); + webClient.get().uri(POLICIES_VCPE_VERSION1).accept(APPLICATION_JSON) + .exchange().expectStatus().isNotFound(); + } + + @Test + void getPolicies() { + var policyTypeFile = "policytypes/onap.policies.monitoring.tcagen2.yaml"; + performPostRequestIsCreated(policyTypeFile, "/policytypes"); + + for (String resourceName : TOSCA_POLICY_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, POLICYTYPES_TCA_POLICIES); + } + + var response = performGetRequestAndCollectResponse(POLICIES); + assertThat(response.getToscaTopologyTemplate().getPolicies()).isNotEmpty(); + } + + @Test + void getPolicies_FetchTypeInvalid() { + webClient.get().uri("/policies?mode=RANDOM").accept(APPLICATION_JSON, APPLICATION_YAML) + .exchange().expectStatus().isOk(); + } + + @Test + void getSpecificPolicy() { + var policyTypeFile = "policytypes/onap.policies.monitoring.tcagen2.yaml"; + performPostRequestIsCreated(policyTypeFile, "/policytypes"); + + for (String resourceName : TOSCA_POLICY_RESOURCE_NAMES) { + performPostRequestIsCreated(resourceName, POLICYTYPES_TCA_POLICIES); + } + + var response = performGetRequestAndCollectResponse(POLICIES_VCPE_VERSION1); + assertThat(response.getToscaTopologyTemplate().getPolicies()).hasSize(1); + } + + protected MediaType getMediaType(String resourceName) { + if (resourceName.endsWith(".json")) { + return MediaType.APPLICATION_JSON; + } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) { + return APPLICATION_YAML; + } + return null; + } + + private void performPostRequestIsCreated(String resourceName, String urlTemplate) { + var mediaType = getMediaType(resourceName); + mediaType = getMediaType(resourceName) == null ? APPLICATION_JSON : mediaType; + var body = ResourceUtils.getResourceAsString(resourceName); + + webClient.post().uri(urlTemplate).contentType(mediaType) + .bodyValue(body).exchange().expectStatus().isCreated(); + } + + private ToscaServiceTemplate performGetRequestAndCollectResponse(String urlTemplate) { + var response = webClient.get().uri(urlTemplate).accept(APPLICATION_JSON, APPLICATION_YAML).exchange() + .expectStatus().isOk().expectBody(String.class); + assertNotNull(response.returnResult()); + var contentType = response.returnResult().getResponseHeaders().getContentType(); + assert contentType != null; + ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); + + try { + if (contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) { + serviceTemplate = new StandardCoder() + .decode(response.returnResult().getResponseBody(), ToscaServiceTemplate.class); + } else if (contentType.isCompatibleWith(APPLICATION_YAML)) { + serviceTemplate = new StandardYamlCoder() + .decode(response.returnResult().getResponseBody(), ToscaServiceTemplate.class); + } + } catch (CoderException e) { + throw new RuntimeException(e); + } + + return serviceTemplate; + } + + private void performGetRequest(String urlTemplate) { + webClient.get().uri(urlTemplate).accept(APPLICATION_JSON, APPLICATION_YAML).exchange() + .expectStatus().isOk(); + } + + private void performDeleteRequest(String urlTemplate) { + webClient.delete().uri(urlTemplate).exchange().expectStatus().isOk(); + } +}
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/e2e/TestNodeTemplateControllerE2E.java b/main/src/test/java/org/onap/policy/api/main/rest/e2e/TestNodeTemplateControllerE2E.java new file mode 100644 index 00000000..ab0c826e --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/e2e/TestNodeTemplateControllerE2E.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest.e2e; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import jakarta.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.errors.concepts.ErrorResponse; +import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.client.ExchangeFilterFunctions; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) +@ActiveProfiles({"default", "test"}) +@AutoConfigureWebTestClient +class TestNodeTemplateControllerE2E { + + @Autowired + WebTestClient webClient; + + protected static final MediaType APPLICATION_YAML = new MediaType("application", "yaml"); + protected static final MediaType APPLICATION_JSON = new MediaType("application", "json"); + + private static final String TOSCA_NODE_TEMPLATE_RESOURCE = + "nodetemplates/nodetemplates.metadatasets.input.tosca.json"; + private static final String TOSCA_INVALID_NODE_TYPE = + "nodetemplates/nodetemplates.metadatasets.invalid.nodetype.json"; + private static final String TOSCA_INVALID_TEMPLATE = + "nodetemplates/nodetemplates.metadatasets.no.nodetemplate.json"; + private static final String TOSCA_UPDATE_NODE_TEMPLATES = "nodetemplates/nodetemplates.metadatasets.update.json"; + + private static final String NODE_TEMPLATES = "/nodetemplates"; + private static final String SPECIFIC_NODE_TEMPLATE = "/nodetemplates/apexMetadata_adaptive/versions/1.0.0"; + private static final String INVALID_NODE_TEMPLATE_ID = "/nodetemplates/invalid_template/versions/1.0.0"; + + private final StandardCoder standardCoder = new StandardCoder(); + + @BeforeEach + void beforeEach() { + var filter = ExchangeFilterFunctions.basicAuthentication("policyadmin", "zb!XztG34"); + webClient = webClient.mutate().filter(filter).build(); + } + + @Test + void testCreateToscaNodeTemplates() throws CoderException { + createNodeTemplate(); + + // Send a node type with an invalid value to trigger an error + var body = ResourceUtils.getResourceAsString(TOSCA_INVALID_NODE_TYPE); + + var responseBody = webClient.post().uri(NODE_TEMPLATES).contentType(APPLICATION_JSON) + .bodyValue(body).exchange().expectStatus().is4xxClientError() + .expectBody(String.class).returnResult().getResponseBody(); + + var errorResp = standardCoder.decode(responseBody, ErrorResponse.class); + assertNotNull(errorResp); + assertEquals(Response.Status.NOT_ACCEPTABLE, errorResp.getResponseCode()); + assertThat(errorResp.getErrorMessage()) + .containsPattern("^NODE_TYPE .* for toscaNodeTemplate .* does not exist$"); + + // Send invalid tosca template with no node templates + body = ResourceUtils.getResourceAsString(TOSCA_INVALID_TEMPLATE); + + webClient.post().uri(NODE_TEMPLATES).contentType(APPLICATION_JSON) + .bodyValue(body).exchange().expectStatus().isNotFound(); + } + + + @Test + void testReadNodeTemplates() { + List<ToscaNodeTemplate> nodeTemplateList = getNodeTemplates(NODE_TEMPLATES); + assertNotNull(nodeTemplateList); + assertTrue(nodeTemplateList.isEmpty()); + + createNodeTemplate(); + + nodeTemplateList = getNodeTemplates(NODE_TEMPLATES); + assertNotNull(nodeTemplateList); + assertEquals(3, nodeTemplateList.size()); + + nodeTemplateList = getNodeTemplates(SPECIFIC_NODE_TEMPLATE); + assertNotNull(nodeTemplateList); + assertEquals(1, nodeTemplateList.size()); + assertEquals("apexMetadata_adaptive", nodeTemplateList.get(0).getName()); + } + + @Test + void testUpdateNodeTemplates() throws Exception { + createNodeTemplate(); + + var updateBody = ResourceUtils.getResourceAsString(TOSCA_UPDATE_NODE_TEMPLATES); + var updateResp = webClient.put().uri(NODE_TEMPLATES).contentType(APPLICATION_JSON) + .bodyValue(updateBody).exchange().expectStatus().isOk().expectBody(String.class); + + ToscaServiceTemplate response = standardCoder + .decode(updateResp.returnResult().getResponseBody(), ToscaServiceTemplate.class); + assertNotNull(response); + assertFalse(response.getToscaTopologyTemplate().getNodeTemplates().isEmpty()); + String updatedValue = "" + response.getToscaTopologyTemplate().getNodeTemplates().get("apexMetadata_grpc") + .getMetadata().get("state"); + assertEquals("passive", updatedValue); + + var invalidUpdateBody = ResourceUtils.getResourceAsString(TOSCA_INVALID_NODE_TYPE); + var responseBody = webClient.put().uri(NODE_TEMPLATES).contentType(APPLICATION_JSON) + .bodyValue(invalidUpdateBody).exchange().expectStatus().is4xxClientError() + .expectBody(String.class).returnResult().getResponseBody(); + var error = standardCoder.decode(responseBody, ErrorResponse.class); + assertNotNull(error); + assertThat(error.getErrorMessage()) + .containsPattern("^NODE_TYPE .* for toscaNodeTemplate .* does not exist$"); + + // Send invalid tosca template with no node templates + invalidUpdateBody = ResourceUtils.getResourceAsString(TOSCA_INVALID_TEMPLATE); + responseBody = webClient.put().uri(NODE_TEMPLATES).contentType(APPLICATION_JSON) + .bodyValue(invalidUpdateBody).exchange().expectStatus().isNotFound() + .expectBody(String.class).returnResult().getResponseBody(); + error = standardCoder.decode(responseBody, ErrorResponse.class); + assertNotNull(error); + assertThat(error.getErrorMessage()).contains("node templates not present on the service template"); + } + + @Test + void testDeleteNodeTemplates() { + createNodeTemplate(); + + webClient.delete().uri(SPECIFIC_NODE_TEMPLATE).exchange().expectStatus().isOk(); + + var nodeTemplateList = getNodeTemplates(NODE_TEMPLATES); + assertEquals(2, nodeTemplateList.size()); + + // Send invalid id + webClient.delete().uri(INVALID_NODE_TEMPLATE_ID).exchange().expectStatus().isNotFound(); + } + + private void createNodeTemplate() { + var body = ResourceUtils.getResourceAsString(TOSCA_NODE_TEMPLATE_RESOURCE); + webClient.post().uri(NODE_TEMPLATES).contentType(APPLICATION_JSON) + .bodyValue(body).exchange().expectStatus().isCreated(); + } + + private List<ToscaNodeTemplate> getNodeTemplates(String uri) { + List<ToscaNodeTemplate> toscaNodeTemplateList = new ArrayList<>(); + + var response = webClient.get().uri(uri).accept(APPLICATION_JSON, APPLICATION_YAML) + .exchange() + .expectStatus().isOk() + .expectBody(String.class); + assertNotNull(response.returnResult()); + var contentType = response.returnResult().getResponseHeaders().getContentType(); + assert contentType != null; + var rawBody = response.returnResult().getResponseBody(); + try { + for (Object node : standardCoder.convert(rawBody, List.class)) { + toscaNodeTemplateList.add(standardCoder.convert(node, ToscaNodeTemplate.class)); + } + } catch (CoderException e) { + fail(e.getMessage()); + } + return toscaNodeTemplateList; + } +} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/healthcheck/TestHealthCheckProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/healthcheck/TestHealthCheckProvider.java new file mode 100644 index 00000000..cec2a1af --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/healthcheck/TestHealthCheckProvider.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest.provider.healthcheck; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.policy.api.main.exception.PolicyApiRuntimeException; +import org.onap.policy.api.main.service.ToscaServiceTemplateService; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; + +class TestHealthCheckProvider { + + @InjectMocks + private HealthCheckProvider healthCheckProvider; + + @Mock + private ToscaServiceTemplateService toscaService; + + AutoCloseable closeable; + + @BeforeEach + void before() { + closeable = MockitoAnnotations.openMocks(this); + } + + @AfterEach + void after() throws Exception { + closeable.close(); + } + + @Test + void performHealthCheck() { + Mockito.when(toscaService.getDefaultJpaToscaServiceTemplate()) + .thenReturn(new JpaToscaServiceTemplate()); + + var result = healthCheckProvider.performHealthCheck(); + assertEquals(200, result.getCode()); + assertTrue(result.isHealthy()); + } + + @Test + void performHealthCheck_NotHealthy() { + Mockito.when(toscaService.getDefaultJpaToscaServiceTemplate()) + .thenThrow(new PolicyApiRuntimeException("Error")); + + var result = healthCheckProvider.performHealthCheck(); + assertEquals(503, result.getCode()); + assertFalse(result.isHealthy()); + } +}
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java b/main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java deleted file mode 100644 index 8e9bf70d..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * Copyright (C) 2022-2023 Nordix Foundation. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.api.main.rest.utils; - -import jakarta.ws.rs.client.Client; -import jakarta.ws.rs.client.ClientBuilder; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.client.Invocation; -import jakarta.ws.rs.client.WebTarget; -import jakarta.ws.rs.core.Response; -import java.security.SecureRandom; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.junit.jupiter.api.Assertions; -import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; -import org.onap.policy.common.gson.GsonMessageBodyHandler; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.common.utils.coder.StandardYamlCoder; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; - -/** - * Util class to perform REST unit tests. - */ -public class CommonTestRestController { - - protected static final String APP_JSON = "application/json"; - protected static final String APP_YAML = "application/yaml"; - - protected static final StandardCoder standardCoder = new StandardCoder(); - protected static StandardYamlCoder standardYamlCoder = new StandardYamlCoder(); - - protected static final String HTTPS_PREFIX = "https://localhost:"; - protected static final String CONTEXT_PATH = "/policy/api/v1/"; - - protected void testSwagger(final int apiPort) throws Exception { - final Invocation.Builder invocationBuilder = sendHttpsRequest("v3/api-docs", APP_JSON, apiPort); - final String resp = invocationBuilder.get(String.class); - Assertions.assertTrue( - (resp).contains("{\"openapi\":\"3.0.1\",\"info\":{\"title\":\"Policy Framework Lifecycle API\"")); - } - - protected Response createResource(String endpoint, String resourceName, int apiPort) - throws Exception { - - ToscaServiceTemplate rawServiceTemplate = getRawServiceTemplate(resourceName); - String mediaType = getMediaType(resourceName); - mediaType = mediaType == null ? APP_JSON : mediaType; - - final Invocation.Builder invocationBuilder; - invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); - Entity<ToscaServiceTemplate> entity = Entity.entity(rawServiceTemplate, mediaType); - return invocationBuilder.post(entity); - } - - protected Response readResource(String endpoint, String mediaType, int apiPort) throws Exception { - - final Invocation.Builder invocationBuilder; - invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); - return invocationBuilder.get(); - } - - protected Response deleteResource(String endpoint, String mediaType, int apiPort) throws Exception { - - final Invocation.Builder invocationBuilder; - invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); - return invocationBuilder.delete(); - } - - protected Response updateResource(String endpoint, String resourceName, String mediaType, int apiPort) - throws Exception { - - ToscaServiceTemplate rawServiceTemplate = getRawServiceTemplate(resourceName); - - final Invocation.Builder invocationBuilder; - invocationBuilder = sendHttpsRequest(endpoint, mediaType, apiPort); - Entity<ToscaServiceTemplate> entity = Entity.entity(rawServiceTemplate, mediaType); - return invocationBuilder.put(entity); - } - - protected ToscaServiceTemplate decodeJson(String resourceName) throws CoderException { - return standardCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class); - } - - protected ToscaServiceTemplate decodeYaml(String resourceName) throws CoderException { - return standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class); - } - - protected Invocation.Builder sendHttpsRequest( - final String endpoint, String mediaType, int apiPort) throws Exception { - - final TrustManager[] noopTrustManager = NetworkUtil.getAlwaysTrustingManager(); - - final SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, noopTrustManager, new SecureRandom()); - final ClientBuilder clientBuilder = - ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); - final Client client = clientBuilder.build(); - final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34"); - client.register(feature); - - client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); - if (APP_JSON.equalsIgnoreCase(mediaType)) { - client.register(GsonMessageBodyHandler.class); - } else if (APP_YAML.equalsIgnoreCase(mediaType)) { - client.register(YamlMessageBodyHandler.class); - } - - final WebTarget webTarget = client.target(HTTPS_PREFIX + apiPort + CONTEXT_PATH + endpoint); - - final Invocation.Builder invocationBuilder = webTarget.request(mediaType); - - if (!NetworkUtil.isTcpPortOpen("localhost", apiPort, 60, 1000L)) { - throw new IllegalStateException("cannot connect to port " + apiPort); - } - return invocationBuilder; - } - - private ToscaServiceTemplate getRawServiceTemplate(String resourceName) throws CoderException { - ToscaServiceTemplate rawServiceTemplate = new ToscaServiceTemplate(); - if (APP_JSON.equals(getMediaType(resourceName))) { - rawServiceTemplate = decodeJson(resourceName); - } else if (APP_YAML.equals(getMediaType(resourceName))) { - rawServiceTemplate = decodeYaml(resourceName); - } - return rawServiceTemplate; - } - - private String getMediaType(String resourceName) { - if (resourceName.endsWith(".json")) { - return APP_JSON; - } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) { - return APP_YAML; - } - return null; - } - -} diff --git a/main/src/test/java/org/onap/policy/api/main/service/TestNodeTemplateService.java b/main/src/test/java/org/onap/policy/api/main/service/TestNodeTemplateService.java index 265f5271..b48306ff 100644 --- a/main/src/test/java/org/onap/policy/api/main/service/TestNodeTemplateService.java +++ b/main/src/test/java/org/onap/policy/api/main/service/TestNodeTemplateService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy API * ================================================================================ - * Copyright (C) 2022-2023 Nordix Foundation. All rights reserved. + * Copyright (C) 2022-2024 Nordix Foundation. 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,6 +25,7 @@ package org.onap.policy.api.main.service; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Optional; import org.junit.jupiter.api.AfterEach; @@ -41,6 +42,7 @@ import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.YamlJsonTranslator; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeType; @@ -115,11 +117,21 @@ class TestNodeTemplateService { @Test void testNodeTemplateUpdate() { - Mockito.when(nodeTypeRepository.findById(Mockito.any())).thenReturn(Optional.of(new JpaToscaNodeType())); Mockito.when(nodeTemplateRepository.findById(Mockito.any())).thenReturn(Optional.of( new JpaToscaNodeTemplate())); assertDoesNotThrow(() -> nodeTemplateService.updateToscaNodeTemplates( new JpaToscaServiceTemplate(updatedToscaServiceTemplate))); } + + @Test + void testNodeTemplateUpdate_Exception() { + Mockito.when(nodeTypeRepository.findById(Mockito.any())).thenReturn(Optional.of(new JpaToscaNodeType())); + Mockito.when(nodeTemplateRepository.findById(Mockito.any())).thenReturn(Optional.empty()); + var updatedObj = new JpaToscaServiceTemplate(updatedToscaServiceTemplate); + assertThrows(PfModelRuntimeException.class, + () -> nodeTemplateService.updateToscaNodeTemplates(updatedObj)); + + assertThrows(NullPointerException.class, () -> nodeTemplateService.updateToscaNodeTemplates(null)); + } } diff --git a/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateForNodeTemplate.java b/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateForNodeTemplate.java index fee7f403..284d3a8c 100644 --- a/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateForNodeTemplate.java +++ b/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateForNodeTemplate.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy API * ================================================================================ - * Copyright (C) 2022-2023 Nordix Foundation. All rights reserved. + * Copyright (C) 2022-2024 Nordix Foundation. 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. @@ -50,11 +50,6 @@ class TestToscaServiceTemplateForNodeTemplate extends TestCommonToscaServiceTemp @InjectMocks private ToscaServiceTemplateService toscaServiceTemplateService; - @BeforeEach - public void setUp() { - super.setUp(); - } - /** * Fetch json files required for the tests. * diff --git a/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyCrud.java b/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyCrud.java index 14d9056e..ee3f9908 100644 --- a/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyCrud.java +++ b/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyCrud.java @@ -3,7 +3,7 @@ * ONAP Policy API * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2020, 2022 Bell Canada. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -32,7 +32,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import jakarta.ws.rs.core.Response; import java.util.Optional; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -71,7 +70,6 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic private static final String POLICY_TYPE_RESOURCE_OPERATIONAL_DROOLS = "policytypes/onap.policies.controlloop.operational.common.Drools.yaml"; private static final String POLICY_RESOURCE_OPERATIONAL = "policies/vCPE.policy.operational.input.tosca.json"; - private static final String POLICY_TYPE_OPERATIONAL_DROOLS = "onap.policies.controlloop.operational.common.Drools"; @Mock private PdpGroupService pdpGroupService; @@ -79,11 +77,6 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic @InjectMocks private ToscaServiceTemplateService toscaServiceTemplateService; - @BeforeEach - public void setUp() { - super.setUp(); - } - @Test void testFetchPolicies() { Mockito.when(toscaServiceTemplateRepository.findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, @@ -114,7 +107,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic @Test void testCreatePolicy() throws Exception { assertThatThrownBy(() -> toscaServiceTemplateService - .createPolicy("dummy", "1.0.0", new ToscaServiceTemplate())) + .createPolicy(new ToscaServiceTemplate())) .hasMessage("topology template not specified on service template"); var policyTypeServiceTemplate = standardYamlCoder @@ -129,7 +122,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var badPolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_BAD_POLICYTYPE_ID); var badPolicyServiceTemplate = standardCoder.decode(badPolicyString, ToscaServiceTemplate.class); - toscaServiceTemplateService.createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + toscaServiceTemplateService.createPolicy( badPolicyServiceTemplate); }).hasMessage( "Version not specified, the version of this TOSCA entity must be specified in " @@ -139,7 +132,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var badPolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_BAD_POLICYTYPE_VERSION); var badPolicyServiceTemplate = standardCoder.decode(badPolicyString, ToscaServiceTemplate.class); - toscaServiceTemplateService.createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + toscaServiceTemplateService.createPolicy( badPolicyServiceTemplate); }).hasMessageContaining( "item \"policy type\" value \"onap.policies.monitoring.cdap.tca.hi.lo.app:2.0.0\" INVALID, not found"); @@ -148,14 +141,14 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var badPolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_NO_POLICY_VERSION); var badPolicyServiceTemplate = standardCoder.decode(badPolicyString, ToscaServiceTemplate.class); - toscaServiceTemplateService.createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + toscaServiceTemplateService.createPolicy( badPolicyServiceTemplate); }).hasMessageContaining("item \"version\" value \"0.0.0\" INVALID, is null"); var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); assertFalse(createPolicyResponseFragment.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); @@ -163,7 +156,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var badPolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_DIFFERENT_FIELDS); var badPolicyServiceTemplate = standardCoder.decode(badPolicyString, ToscaServiceTemplate.class); - toscaServiceTemplateService.createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", + toscaServiceTemplateService.createPolicy( badPolicyServiceTemplate); }).hasMessageContaining( "item \"entity\" value \"onap.restart.tca:1.0.0\" INVALID, " + "does not equal existing entity"); @@ -185,7 +178,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_OPERATIONAL); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); serviceTemplate = - toscaServiceTemplateService.createPolicy(POLICY_TYPE_OPERATIONAL_DROOLS, "1.0.0", policyServiceTemplate); + toscaServiceTemplateService.createPolicy(policyServiceTemplate); assertFalse(serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); } @@ -284,7 +277,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic @Test void testDeletePolicy() throws CoderException { - assertThatThrownBy(() -> toscaServiceTemplateService.deletePolicy("dummy", "1.0.0", "dummy", "1.0.0")) + assertThatThrownBy(() -> toscaServiceTemplateService.deletePolicy("dummy", "1.0.0")) .hasMessage("no policies found"); var policyTypeServiceTemplate = standardYamlCoder @@ -295,7 +288,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); assertFalse(createPolicyResponseFragment.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); @@ -303,18 +296,18 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic Mockito.doThrow(new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, exceptionMessage)) .when(pdpGroupService).assertPolicyNotDeployedInPdpGroup("onap.restart.tca", "1.0.0"); assertThatThrownBy(() -> toscaServiceTemplateService - .deletePolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", "onap.restart.tca", "1.0.0")) + .deletePolicy("onap.restart.tca", "1.0.0")) .hasMessage(exceptionMessage); Mockito.doNothing().when(pdpGroupService).assertPolicyNotDeployedInPdpGroup("onap.restart.tca", "1.0.0"); var deletePolicyResponseFragment = toscaServiceTemplateService - .deletePolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", "onap.restart.tca", "1.0.0"); + .deletePolicy("onap.restart.tca", "1.0.0"); assertFalse(deletePolicyResponseFragment.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); mockDbServiceTemplate(serviceTemplate, deletePolicyResponseFragment, Operation.DELETE_POLICY); assertThatThrownBy(() -> toscaServiceTemplateService - .deletePolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", "onap.restart.tca", "1.0.0")) + .deletePolicy("onap.restart.tca", "1.0.0")) .hasMessageContaining("no policies found"); } @@ -330,7 +323,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); assertThat(serviceTemplate.getToscaTopologyTemplate().getPolicies()).hasSize(1); @@ -353,7 +346,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); assertThat(serviceTemplate.getToscaTopologyTemplate().getPolicies()).hasSize(1); @@ -375,7 +368,7 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); assertNotNull(serviceTemplate.getToscaTopologyTemplate().getPolicies()); assertThat(serviceTemplate.getToscaTopologyTemplate().getPolicies()).hasSize(1); @@ -395,11 +388,11 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); assertThat(createPolicyResponseFragment.getToscaTopologyTemplate().getPolicies()).hasSize(1); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); - serviceTemplate = toscaServiceTemplateService.deletePolicy(null, null, "onap.restart.tca", "1.0.0"); + serviceTemplate = toscaServiceTemplateService.deletePolicy("onap.restart.tca", "1.0.0"); assertThat(serviceTemplate.getToscaTopologyTemplate().getPolicies()).hasSize(1); } @@ -413,14 +406,14 @@ class TestToscaServiceTemplateServiceForPolicyCrud extends TestCommonToscaServic var policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE); var policyServiceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class); var createPolicyResponseFragment = toscaServiceTemplateService - .createPolicy("onap.policies.monitoring.cdap.tca.hi.lo.app", "1.0.0", policyServiceTemplate); + .createPolicy(policyServiceTemplate); assertThat(createPolicyResponseFragment.getToscaTopologyTemplate().getPolicies()).hasSize(1); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); - assertThatThrownBy(() -> toscaServiceTemplateService.deletePolicy(null, null, "onap.restart.tca", "2.0.0")) + assertThatThrownBy(() -> toscaServiceTemplateService.deletePolicy("onap.restart.tca", "2.0.0")) .hasMessageContaining("not found"); - assertThatThrownBy(() -> toscaServiceTemplateService.deletePolicy(null, null, + assertThatThrownBy(() -> toscaServiceTemplateService.deletePolicy( "onap.restart.tca.unavailable", "1.0.0")).hasMessageContaining("not found"); } }
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyTypeCrud.java b/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyTypeCrud.java index 9dcb4333..703afce8 100644 --- a/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyTypeCrud.java +++ b/main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyTypeCrud.java @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,9 +86,8 @@ class TestToscaServiceTemplateServiceForPolicyTypeCrud extends TestCommonToscaSe assertThatThrownBy(() -> toscaServiceTemplateService.fetchPolicyTypes("dummy", "dummy")) .hasMessage("policy types for filter ToscaEntityFilter(name=dummy, version=dummy) do not exist"); - // FIXME - // ToscaServiceTemplate serviceTemplate = toscaServiceTemplateService.fetchPolicyTypes(null, null); - // assertFalse(serviceTemplate.getPolicyTypes().isEmpty()); + assertThatThrownBy(() -> toscaServiceTemplateService.fetchPolicyTypes(null, null)) + .hasMessage("policy types for filter ToscaEntityFilter(name=null, version=null) do not exist"); } @Test @@ -169,8 +168,8 @@ class TestToscaServiceTemplateServiceForPolicyTypeCrud extends TestCommonToscaSe var policyServiceTemplate = coder .decode(ResourceUtils.getResourceAsString(POLICY_RESOURCE_MONITORING), ToscaServiceTemplate.class); mockDbServiceTemplate(serviceTemplate, null, null); - var createPolicyResponseFragment = toscaServiceTemplateService.createPolicy("onap.policies.monitoring.tcagen2", - "1.0.0", policyServiceTemplate); + var createPolicyResponseFragment = toscaServiceTemplateService.createPolicy( + policyServiceTemplate); mockDbServiceTemplate(serviceTemplate, createPolicyResponseFragment, Operation.CREATE_POLICY); var exceptionMessage = "policy type onap.policies.monitoring.tcagen2:1.0.0 is in use, " @@ -179,7 +178,7 @@ class TestToscaServiceTemplateServiceForPolicyTypeCrud extends TestCommonToscaSe "1.0.0")).hasMessage(exceptionMessage); var deletePolicyResponseFragment = toscaServiceTemplateService - .deletePolicy("onap.policies.monitoring.tcagen2", "1.0.0", "onap.restart.tca", "1.0.0"); + .deletePolicy("onap.restart.tca", "1.0.0"); assertFalse(deletePolicyResponseFragment.getToscaTopologyTemplate().getPolicies().get(0).isEmpty()); mockDbServiceTemplate(serviceTemplate, deletePolicyResponseFragment, Operation.DELETE_POLICY); diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerExceptionsTest.java b/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerExceptionsTest.java new file mode 100644 index 00000000..8f6f7aea --- /dev/null +++ b/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerExceptionsTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.startstop; + +import static org.mockito.ArgumentMatchers.any; + +import io.netty.handler.codec.CodecException; +import java.util.HashMap; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.onap.policy.api.main.config.PolicyPreloadConfig; +import org.onap.policy.api.main.exception.PolicyApiException; +import org.onap.policy.api.main.service.ToscaServiceTemplateService; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardYamlCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; + +class ApiDatabaseInitializerExceptionsTest { + + @Test + void testInitializeApiDatabase_CoderExceptions() throws CoderException, PfModelException { + var list = List.of("policy", "policyType"); + var mockPolicyPreload = Mockito.mock(PolicyPreloadConfig.class); + Mockito.when(mockPolicyPreload.getPolicies()).thenReturn(list); + Mockito.when(mockPolicyPreload.getPolicyTypes()).thenReturn(list); + + var serviceTemplate = new ToscaServiceTemplate(); + serviceTemplate.setPolicyTypes(new HashMap<>()); + var mockServiceTemplate = Mockito.mock(ToscaServiceTemplateService.class); + Mockito.when(mockServiceTemplate.getFilteredPolicyTypes(any())).thenReturn(serviceTemplate); + + var mockYamlCoder = Mockito.mock(StandardYamlCoder.class); + Mockito.when(mockYamlCoder.decode((String) any(), any())) + .thenThrow(new CodecException("fail")); + + var databaseService = new ApiDatabaseInitializer(mockServiceTemplate, mockPolicyPreload); + Assertions.assertThrows(PolicyApiException.class, databaseService::loadData); + } + + @Test + void testInitializeApiDatabase_CantFindResourceExceptions() throws PfModelException { + var list = List.of("policy", "policyType"); + var mockPolicyPreload = Mockito.mock(PolicyPreloadConfig.class); + Mockito.when(mockPolicyPreload.getPolicies()).thenReturn(list); + Mockito.when(mockPolicyPreload.getPolicyTypes()).thenReturn(list); + + var serviceTemplate = new ToscaServiceTemplate(); + serviceTemplate.setPolicyTypes(new HashMap<>()); + var mockServiceTemplate = Mockito.mock(ToscaServiceTemplateService.class); + Mockito.when(mockServiceTemplate.getFilteredPolicyTypes(any())).thenReturn(serviceTemplate); + + try (MockedStatic<ResourceUtils> utilities = Mockito.mockStatic(ResourceUtils.class)) { + utilities.when(() -> ResourceUtils.getResourceAsString(any())).thenReturn(null); + } + + var databaseService = new ApiDatabaseInitializer(mockServiceTemplate, mockPolicyPreload); + Assertions.assertThrows(PolicyApiException.class, databaseService::loadData); + } +}
\ No newline at end of file diff --git a/main/src/test/resources/application-test-mvc.yaml b/main/src/test/resources/application-test-mvc.yaml new file mode 100644 index 00000000..7e0fa5ed --- /dev/null +++ b/main/src/test/resources/application-test-mvc.yaml @@ -0,0 +1,14 @@ +spring: + datasource: + driverClassName: org.h2.Driver + generate-unique-name: true + jpa: + hibernate: + ddl-auto: create-drop + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + implicit-strategy: org.onap.policy.common.spring.utils.CustomImplicitNamingStrategy + open-in-view: false +server: + servlet: + application-display-name: test-mvc diff --git a/main/src/test/resources/application-test.yaml b/main/src/test/resources/application-test.yaml index 329d96be..82da86fe 100644 --- a/main/src/test/resources/application-test.yaml +++ b/main/src/test/resources/application-test.yaml @@ -4,7 +4,7 @@ spring: driverClassName: org.h2.Driver jpa: hibernate: - ddl-auto: update + ddl-auto: create-drop naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl implicit-strategy: org.onap.policy.common.spring.utils.CustomImplicitNamingStrategy |