aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/test/java/org/onap
diff options
context:
space:
mode:
authoradheli.tavares <adheli.tavares@est.tech>2024-07-03 09:24:46 +0100
committeradheli.tavares <adheli.tavares@est.tech>2024-07-03 10:17:33 +0100
commitcfa75756c40aaabcb236aafca6f5a56f3ce88d85 (patch)
tree6726f0de314aa6e6e20faa1cfbc4d0a2e2523b20 /main/src/test/java/org/onap
parent64e621f7ffe22975e6700f67b8a1fe7c92e2e958 (diff)
Code coverage and sonar fixes
- added web mvc tests to cover controller exception cases - added webclient tests with full spring support to replace old style of Invoker - fixed some sonar issues - refactored a test still using @RunWith from junit4 Issue-ID: POLICY-5067 Change-Id: I4d3e77c32a603bdfeca4db76f00acf38830ef250 Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
Diffstat (limited to 'main/src/test/java/org/onap')
-rw-r--r--main/src/test/java/org/onap/policy/api/contract/ApiContractTest.java143
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/TestApiRestController.java383
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java700
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java31
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/TestNodeTemplateController.java264
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/e2e/TestApiRestControllerE2E.java449
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/e2e/TestNodeTemplateControllerE2E.java199
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/provider/healthcheck/TestHealthCheckProvider.java77
-rw-r--r--main/src/test/java/org/onap/policy/api/main/rest/utils/CommonTestRestController.java162
-rw-r--r--main/src/test/java/org/onap/policy/api/main/service/TestNodeTemplateService.java16
-rw-r--r--main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateForNodeTemplate.java7
-rw-r--r--main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyCrud.java49
-rw-r--r--main/src/test/java/org/onap/policy/api/main/service/TestToscaServiceTemplateServiceForPolicyTypeCrud.java13
-rw-r--r--main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerExceptionsTest.java82
14 files changed, 1437 insertions, 1138 deletions
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