From d4dd779aa66be0e046ecb1938fb532312cfe7680 Mon Sep 17 00:00:00 2001 From: "andre.schmid" Date: Mon, 20 Jul 2020 17:48:48 +0100 Subject: Upload policy feature Implements an upload feature that can be enable/disabled through configuration properties. An upload endpoint must be provided also by configuration. The upload has similar feature as the download, but it sends the file to the provided endpoint instead, converting it to TOSCA YAML. Creates an configuration endpoint so the front-end can read it. Introduces a pub/sub feature in the front-end so it can asynchronous read configuration information and send configuration ready message to components that depends on it. Issue-ID: POLICY-2751 Signed-off-by: andre.schmid Change-Id: I5e8e91616a7d4dc69e6739604fcd36528cce0028 --- .../editors/apex/rest/ApexEditorStartupTest.java | 2 + .../gui/editors/apex/rest/RestInterfaceTest.java | 2 + .../rest/UploadPluginConfigParametersTest.java | 85 ++++++++ .../rest/handling/ApexEditorRestResourceTest.java | 3 +- .../handling/ConfigurationRestResourceTest.java | 64 ++++++ .../converter/tosca/ApexConfigProcessorTest.java | 113 +++++++++++ .../converter/tosca/PolicyToscaConverterTest.java | 187 ++++++++++++++++++ .../converter/tosca/PolicyUploadHandlerTest.java | 200 +++++++++++++++++++ .../tosca/ToscaTemplateProcessorTest.java | 216 +++++++++++++++++++++ .../plugin/upload/UploadPluginClientTest.java | 71 +++++++ 10 files changed, 942 insertions(+), 1 deletion(-) create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java create mode 100644 gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java (limited to 'gui-editors/gui-editor-apex/src/test/java') diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java index 1dc47cd..c80b816 100644 --- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.TimeUnit; import org.junit.Test; +import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.gui.editors.apex.rest.ApexEditorMain.EditorState; /** @@ -385,6 +386,7 @@ public class ApexEditorStartupTest { * @throws InterruptedException if the test is interrupted */ private String runEditor(final String[] args) throws InterruptedException { + ParameterService.clear(); final ByteArrayOutputStream outBaStream = new ByteArrayOutputStream(); final PrintStream outStream = new PrintStream(outBaStream); diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java index 238e3b9..60a2012 100644 --- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java @@ -46,6 +46,7 @@ import org.onap.policy.apex.model.basicmodel.handling.ApexModelStringWriter; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.gui.editors.apex.rest.ApexEditorMain.EditorState; @@ -74,6 +75,7 @@ public class RestInterfaceTest { */ @BeforeClass public static void setUp() throws Exception { + ParameterService.clear(); // Start the editor editorMain = new ApexEditorMain(EDITOR_MAIN_ARGS, System.out); // prevent a stray stdin value from killing the editor diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java new file mode 100644 index 0000000..3f743a7 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java @@ -0,0 +1,85 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest; + + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; +import org.junit.Test; +import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey; + +public class UploadPluginConfigParametersTest { + + @Test + public void setupPropertiesTest() { + final String expectedUrl = "aUrl"; + final boolean expectedEnabled = true; + System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), expectedUrl); + System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(expectedEnabled)); + final UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters(); + final String url = uploadPluginConfigParameters.getUrl(); + final Boolean isEnabled = uploadPluginConfigParameters.isEnabled(); + assertThat(url).isEqualTo(expectedUrl); + assertThat(isEnabled).isEqualTo(expectedEnabled); + } + + @Test + public void testGetValue() { + final String expectedUrl = "aUrl"; + final boolean expectedEnabled = true; + System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), expectedUrl); + System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(expectedEnabled)); + UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters(); + Optional actualUrl = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.URL); + assertThat(actualUrl).isPresent().contains(expectedUrl); + Optional actualEnabled = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.ENABLE); + assertThat(actualEnabled).isPresent().contains(expectedEnabled); + + System.clearProperty(PolicyUploadPluginConfigKey.URL.getKey()); + uploadPluginConfigParameters = new UploadPluginConfigParameters(); + actualUrl = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.URL); + assertThat(actualUrl).isNotPresent(); + + System.clearProperty(PolicyUploadPluginConfigKey.ENABLE.getKey()); + uploadPluginConfigParameters = new UploadPluginConfigParameters(); + actualEnabled = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.ENABLE); + assertThat(actualEnabled).isPresent(); + assertThat(actualEnabled.get()).isFalse(); + } + + @Test + public void testValidate() { + final String expectedUrl = "aUrl"; + final boolean expectedEnabled = true; + System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), expectedUrl); + System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(expectedEnabled)); + UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters(); + assertThat(uploadPluginConfigParameters.isValid()).isTrue(); + + System.clearProperty(PolicyUploadPluginConfigKey.URL.getKey()); + uploadPluginConfigParameters = new UploadPluginConfigParameters(); + assertThat(uploadPluginConfigParameters.isValid()).isFalse(); + + System.clearProperty(PolicyUploadPluginConfigKey.ENABLE.getKey()); + uploadPluginConfigParameters = new UploadPluginConfigParameters(); + assertThat(uploadPluginConfigParameters.isValid()).isTrue(); + } +} \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java index 934ca7e..9b0ce32 100644 --- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java @@ -28,6 +28,7 @@ import java.io.IOException; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; +import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; @@ -43,7 +44,7 @@ import org.onap.policy.common.utils.resources.TextFileUtils; public class ApexEditorRestResourceTest extends JerseyTest { @Override protected Application configure() { - return new ResourceConfig(ApexEditorRestResource.class); + return new ResourceConfig(ApexEditorRestResource.class).register(MultiPartFeature.class); } @Test diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java new file mode 100644 index 0000000..3820240 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java @@ -0,0 +1,64 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; +import org.onap.policy.apex.model.modelapi.ApexApiResult; +import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; +import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey; + +public class ConfigurationRestResourceTest extends JerseyTest { + + private String anUrl; + private Boolean isEnabled; + + @Override + protected Application configure() { + anUrl = "url"; + isEnabled = true; + System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), anUrl); + System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(isEnabled)); + final UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters(); + ParameterService.clear(); + ParameterService.register(uploadPluginConfigParameters); + return new ResourceConfig(ConfigurationRestResource.class); + } + + @Test + public void testShowSuccess() { + final Response response = target("/editor/config").request().get(); + assertEquals(Status.OK.getStatusCode(), response.getStatus()); + final ApexApiResult apexApiResult = response.readEntity(ApexApiResult.class); + assertEquals(Result.SUCCESS, apexApiResult.getResult()); + final String message = apexApiResult.getMessage(); + assertThat(message).contains(String.format("\"%s\":\"%s\"", PolicyUploadPluginConfigKey.URL.getKey(), anUrl)) + .contains(String.format("\"%s\":%s", PolicyUploadPluginConfigKey.ENABLE.getKey(), isEnabled)); + } +} \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java new file mode 100644 index 0000000..a12f7e1 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling.converter.tosca; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.is; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor.ErrorMessage.INVALID_APEX_CONFIG; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor.ErrorMessage.INVALID_ENTRY; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor.ErrorMessage.MISSING_ENTRY; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.ENGINE_SERVICE_PARAMETERS; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import org.junit.Test; +import org.onap.policy.common.utils.coder.StandardCoder; + +public class ApexConfigProcessorTest { + + private final ApexConfigProcessor apexConfigProcessor = new ApexConfigProcessor(new StandardCoder()); + private final Path testResourcesPath = Paths.get("src", "test", "resources", "processor"); + + @Test + public void testProcessSuccess() throws IOException { + final String fileName = "ApexConfig.json"; + final ProcessedTemplate process; + try (final FileInputStream fileInputStream = readFileAsStream(fileName)) { + process = apexConfigProcessor.process(fileInputStream); + } + assertThat("Template should be valid", process.isValid(), is(true)); + final String expectedContent = readFileAsString(fileName); + assertThat("Content should be the same", process.getContent(), is(expectedContent)); + } + + @Test + public void testProcessMissingPoliciesEntry() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ApexConfig-missing-engineServiceParameters.json")) { + processedTemplate = apexConfigProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(MISSING_ENTRY.getMessage(ENGINE_SERVICE_PARAMETERS.getKey()))); + } + + @Test + public void testProcessInvalidToscaTemplate() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ApexConfig-invalid.json")) { + processedTemplate = apexConfigProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_APEX_CONFIG.getMessage())); + } + + @Test + public void testProcessInvalidEngineServiceParameters() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ApexConfig-invalid-engineServiceParameters.json")) { + processedTemplate = apexConfigProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_ENTRY.getMessage(ENGINE_SERVICE_PARAMETERS.getKey()))); + } + + private void assertProcessedTemplate(final ProcessedTemplate process, boolean isValid, + final List expectedErrorList) { + + assertThat("Template should be valid", process.isValid(), is(isValid)); + if (isValid || expectedErrorList == null) { + return; + } + assertThat("Should contains the expected quantity of errors", + process.getErrorSet().size(), is(expectedErrorList.size())); + expectedErrorList + .forEach(errorMsg -> assertThat("Should contains a specific error message", process.getErrorSet(), + contains(errorMsg))); + } + + private FileInputStream readFileAsStream(final String fileName) throws FileNotFoundException { + final Path path = Paths.get(testResourcesPath.toString(), fileName); + return new FileInputStream(path.toFile()); + } + + private String readFileAsString(final String fileName) throws IOException { + final Path path = Paths.get(testResourcesPath.toString(), fileName); + return Files.readString(path); + } + +} \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java new file mode 100644 index 0000000..ecf896e --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java @@ -0,0 +1,187 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling.converter.tosca; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.ENGINE_SERVICE_PARAMETERS; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.POLICIES; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.POLICY_TYPE_IMPL; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.PROPERTIES; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOPOLOGY_TEMPLATE; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOSCA_DEFINITIONS_VERSION; + +import com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +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.coder.YamlJsonTranslator; +import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.exception.PolicyToscaConverterException; + +public class PolicyToscaConverterTest { + + @Spy + private final StandardCoder standardCoder = new StandardCoder(); + @Spy + private final YamlJsonTranslator yamlJsonTranslator = new YamlJsonTranslator(); + @InjectMocks + private PolicyToscaConverter policyToscaConverter; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testConvertSuccess() throws IOException, PolicyToscaConverterException, CoderException { + final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json")); + final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json")); + final String toscaTemplate = readResourceFileToString(Paths.get("converter", "ToscaTemplate.json")); + final Optional convert = policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate); + assertTrue(convert.isPresent()); + final String convertedYaml = convert.get(); + final StandardYamlCoder standardYamlCoder = new StandardYamlCoder(); + @SuppressWarnings("unchecked") final Map yamlAsMap = + standardYamlCoder.decode(convertedYaml, Map.class); + assertThat(yamlAsMap).containsKeys(TOSCA_DEFINITIONS_VERSION.getKey(), TOPOLOGY_TEMPLATE.getKey()); + @SuppressWarnings("unchecked") final Map topology_template = + (Map) yamlAsMap.get(TOPOLOGY_TEMPLATE.getKey()); + assertThat(topology_template).containsKey(POLICIES.getKey()); + @SuppressWarnings("unchecked") final List policies = + (List) topology_template.get(POLICIES.getKey()); + assertEquals(1, policies.size()); + @SuppressWarnings("unchecked") final Map firstPolicyMap = (Map) policies.get(0); + assertEquals(1, firstPolicyMap.keySet().size()); + @SuppressWarnings("unchecked") final Map firstPolicy = + (Map) firstPolicyMap.get(firstPolicyMap.keySet().iterator().next()); + assertThat(firstPolicy).containsKey(PROPERTIES.getKey()); + @SuppressWarnings("unchecked") final Map propertiesMap = + (Map) firstPolicy.get(PROPERTIES.getKey()); + assertThat(propertiesMap).containsKey(ENGINE_SERVICE_PARAMETERS.getKey()); + @SuppressWarnings("unchecked") final Map engineServiceParametersProperty = + (Map) propertiesMap.get(ENGINE_SERVICE_PARAMETERS.getKey()); + assertThat(engineServiceParametersProperty).containsKey(POLICY_TYPE_IMPL.getKey()); + } + + @Test + public void testConvertInvalidJsonDecode() throws CoderException { + final String invalidJson = "this is an invalid JSON"; + doThrow(CoderException.class).when(standardCoder).decode(eq(invalidJson), eq(JsonObject.class)); + + final String expectedMsg = String.format("Could not convert JSON string to JSON:\n%s", invalidJson); + assertThatThrownBy(() -> policyToscaConverter.convert(invalidJson, invalidJson, invalidJson)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessage(expectedMsg); + } + + @Test + public void testConvertInvalidJsonEncodeToString() throws IOException { + final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json")); + final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json")); + final String toscaTemplate = readResourceFileToString(Paths.get("converter", "ToscaTemplate.json")); + + doThrow(RuntimeException.class).when(yamlJsonTranslator).toYaml(any(JsonObject.class)); + + assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessageContaining("Could not convert JSON Object to YAML:"); + } + + @Test + public void testCouldNotReadFirstPolicy() throws IOException { + final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json")); + final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json")); + final String toscaTemplate1 = + readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-policies.json")); + final String expectedError = + String.format("Could not read the first policy in the '%s' entry under '%s'", + POLICIES.getKey(), TOPOLOGY_TEMPLATE.getKey()); + + assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate1)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessage(expectedError); + final String toscaTemplate2 = + readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-policy.json")); + + assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate2)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessage(expectedError); + } + + @Test + public void testCouldNotReadPolicyProperties() throws IOException { + final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json")); + final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json")); + final String toscaTemplate = + readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-properties.json")); + assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessage(String.format("Could not read the policy '%s' entry", PROPERTIES.getKey())); + } + + @Test + public void testCouldNotReadEngineServiceParameters() throws IOException { + final String apexConfig = + readResourceFileToString(Paths.get("converter", "ApexConfig-engineServiceParameters-notAnObject.json")); + final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json")); + final String toscaTemplate = + readResourceFileToString(Paths.get("converter", "ToscaTemplate.json")); + assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessage( + String.format("Could not read the '%s' in the Apex Config", ENGINE_SERVICE_PARAMETERS.getKey())); + } + + @Test + public void testCouldNotReadTopologyTemplate() throws IOException { + final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json")); + final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json")); + final String toscaTemplate = + readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-topology-template.json")); + assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate)) + .isInstanceOf(PolicyToscaConverterException.class) + .hasMessage( + String.format("Could not read the '%s' entry in the Tosca Template", TOPOLOGY_TEMPLATE.getKey())); + } + + private String readResourceFileToString(final Path filePathFromResources) throws IOException { + final Path resourceDirectory = Paths.get("src", "test", "resources"); + final Path converter = Paths.get(resourceDirectory.toString(), filePathFromResources.toString()); + return Files.readString(converter); + } + +} \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java new file mode 100644 index 0000000..7a6ead7 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java @@ -0,0 +1,200 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling.converter.tosca; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.ws.rs.core.Response; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.modelapi.ApexApiResult; +import org.onap.policy.apex.model.modelapi.ApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; +import org.onap.policy.gui.editors.apex.rest.handling.PolicyUploadHandler; +import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.exception.PolicyToscaConverterException; +import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.UploadPluginClient; +import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.UploadPolicyRequestDto; + +public class PolicyUploadHandlerTest { + + @Mock + private PolicyToscaConverter policyToscaConverter; + @Mock + private ToscaTemplateProcessor toscaTemplateProcessor; + @Mock + private ApexConfigProcessor apexConfigProcessor; + @Mock + private UploadPluginClient uploadPluginClient; + @Mock + private UploadPluginConfigParameters config; + + @InjectMocks + private PolicyUploadHandler policyUploadHandler; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(config.isEnabled()).thenReturn(true); + } + + @Test + public void doUploadResponseSuccessAndFail() throws PolicyToscaConverterException, IOException { + final ApexModel apexModel = mockApexModel(); + final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate(); + processedToscaTemplate.setContent("tosca"); + final ProcessedTemplate processedApexConfig = new ProcessedTemplate(); + processedApexConfig.setContent("apexConfig"); + when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate); + when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig); + when(policyToscaConverter.convert(eq("policy\n"), eq("apexConfig"), eq("tosca"))) + .thenReturn(Optional.of("test")); + when(uploadPluginClient.upload(any(UploadPolicyRequestDto.class))) + .thenReturn(Response.ok().status(201).build()); + + ApexApiResult apexApiResult = policyUploadHandler + .doUpload(apexModel, mock(InputStream.class), mock(InputStream.class)); + + assertThat("Response should be ok", apexApiResult.isOk(), is(true)); + String expectedSuccessMsg = + String.format("Policy '%s' uploaded successfully", apexModel.getPolicyModel().getId()); + assertThat("Response message should be as expected", + apexApiResult.getMessage(), is(expectedSuccessMsg + "\n")); + + when(uploadPluginClient.upload(any(UploadPolicyRequestDto.class))) + .thenReturn(Response.serverError().build()); + + apexApiResult = policyUploadHandler + .doUpload(apexModel, mock(InputStream.class), mock(InputStream.class)); + + assertThat("Response should not be ok", apexApiResult.isNok(), is(true)); + expectedSuccessMsg = + String.format("An error has occurred while uploading the Policy '%s'. Status was %s", + apexModel.getPolicyModel().getId(), 500); + assertThat("Response message should be as expected", + apexApiResult.getMessage(), is(expectedSuccessMsg + "\n")); + } + + @Test + public void doUploadPluginDisabled() throws IOException { + when(config.isEnabled()).thenReturn(false); + + final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate(); + final ProcessedTemplate processedApexConfig = new ProcessedTemplate(); + when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate); + when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig); + final ApexApiResult apexApiResult = policyUploadHandler + .doUpload(mock(ApexModel.class), mock(InputStream.class), mock(InputStream.class)); + + assertThat("Response should not be ok", apexApiResult.isNok(), is(true)); + assertThat("Response message should be as expected", + apexApiResult.getMessage(), is("Upload feature is disabled\n")); + } + + @Test + public void doUploadInvalidToscaTemplate() throws IOException { + when(config.isEnabled()).thenReturn(false); + + final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate(); + final String errorMsg = "an error"; + processedToscaTemplate.addToErrors(Collections.singleton(errorMsg)); + when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate); + final ApexApiResult apexApiResult = policyUploadHandler + .doUpload(mock(ApexModel.class), mock(InputStream.class), mock(InputStream.class)); + + assertThat("Response should not be ok", apexApiResult.isNok(), is(true)); + assertThat("Response message should be as expected", + apexApiResult.getMessage(), is(errorMsg + "\n")); + } + + @Test + public void doUploadInvalidApexConfigTemplate() throws IOException { + when(config.isEnabled()).thenReturn(false); + + when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(new ProcessedTemplate()); + final ProcessedTemplate processedApexConfig = new ProcessedTemplate(); + final String errorMsg = "an error"; + processedApexConfig.addToErrors(Collections.singleton(errorMsg)); + when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig); + final ApexApiResult apexApiResult = policyUploadHandler + .doUpload(mock(ApexModel.class), mock(InputStream.class), mock(InputStream.class)); + + assertThat("Response should not be ok", apexApiResult.isNok(), is(true)); + assertThat("Response message should be as expected", + apexApiResult.getMessage(), is(errorMsg + "\n")); + } + + @Test + public void doUploadConversionFailed() throws PolicyToscaConverterException, IOException { + final ApexModel apexModel = mockApexModel(); + final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate(); + processedToscaTemplate.setContent("tosca"); + final ProcessedTemplate processedApexConfig = new ProcessedTemplate(); + processedApexConfig.setContent("apexConfig"); + when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate); + when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig); + when(policyToscaConverter.convert(eq("policy\n"), eq("apexConfig"), eq("tosca"))) + .thenThrow(PolicyToscaConverterException.class); + when(uploadPluginClient.upload(any(UploadPolicyRequestDto.class))) + .thenReturn(Response.ok().status(201).build()); + + final ApexApiResult apexApiResult = policyUploadHandler + .doUpload(apexModel, mock(InputStream.class), mock(InputStream.class)); + + assertThat("Response should not be ok", apexApiResult.isNok(), is(true)); + final String expectedErrorMsg = String + .format("An error has occurred while uploading the converting the Policy '%s' to YAML.", + apexModel.getPolicyModel().getId()); + assertThat("Response message should be as expected", + apexApiResult.getMessage(), is(expectedErrorMsg + "\n")); + } + + private ApexModel mockApexModel() { + final ApexModel apexModel = mock(ApexModel.class); + final ApexApiResult listModelApexApiResult = new ApexApiResult(); + listModelApexApiResult.addMessage("policy"); + when(apexModel.listModel()).thenReturn(listModelApexApiResult); + final AxPolicyModel axPolicyModel = new AxPolicyModel(); + final AxArtifactKey axArtifactKey = new AxArtifactKey("policyKey", "1.0.0"); + final Map keyInfoMap = new HashMap<>(); + keyInfoMap.put(axArtifactKey, new AxKeyInfo(axArtifactKey)); + final AxKeyInformation axKeyInformation = new AxKeyInformation(axArtifactKey, keyInfoMap); + axPolicyModel.setKeyInformation(axKeyInformation); + when(apexModel.getPolicyModel()).thenReturn(axPolicyModel); + return apexModel; + } +} \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java new file mode 100644 index 0000000..461b26e --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java @@ -0,0 +1,216 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling.converter.tosca; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.is; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.POLICIES; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.PROPERTIES; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOPOLOGY_TEMPLATE; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOSCA_DEFINITIONS_VERSION; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.INVALID_ENTRY; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.INVALID_POLICY; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.INVALID_TOSCA_TEMPLATE; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.MISSING_ENTRY; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.MISSING_POLICY; +import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.ONLY_ONE_POLICY_ALLOWED; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import org.junit.Test; +import org.onap.policy.common.utils.coder.StandardCoder; + +public class ToscaTemplateProcessorTest { + + private final ToscaTemplateProcessor toscaTemplateProcessor = new ToscaTemplateProcessor(new StandardCoder()); + private final Path testResourcesPath = Paths.get("src", "test", "resources", "processor"); + + @Test + public void testProcessSuccess() throws IOException { + final String fileName = "ToscaTemplate.json"; + final ProcessedTemplate process; + try (final FileInputStream fileInputStream = readFileAsStream(fileName)) { + process = toscaTemplateProcessor.process(fileInputStream); + } + assertThat("Template should be valid", process.isValid(), is(true)); + final String expectedContent = readFileAsString(fileName); + assertThat("Content should be the same", process.getContent(), is(expectedContent)); + } + + @Test + public void testProcessMissingPoliciesEntry() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-policies.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, List.of(MISSING_ENTRY.getMessage(POLICIES.getKey()))); + } + + @Test + public void testProcessMissingTopologyTemplate() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-topology-template.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(MISSING_ENTRY.getMessage(TOPOLOGY_TEMPLATE.getKey()))); + } + + @Test + public void testProcessMissingPolicy() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-policy.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, List.of(MISSING_POLICY.getMessage())); + } + + @Test + public void testProcessMissingToscaDefinitionsVersion() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ToscaTemplate-missing-tosca-definitions-version.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(MISSING_ENTRY.getMessage(TOSCA_DEFINITIONS_VERSION.getKey()))); + } + + @Test + public void testProcessMissingProperties() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-properties.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(MISSING_ENTRY.getMessage(PROPERTIES.getKey()))); + } + + @Test + public void testProcessMoreThanOnePolicy() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-more-than-one-policy.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(ONLY_ONE_POLICY_ALLOWED.getMessage())); + } + + @Test + public void testProcessInvalidToscaTemplate() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalid.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_TOSCA_TEMPLATE.getMessage())); + } + + @Test + public void testProcessInvalidEntryToscaDefinitionsVersion() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ToscaTemplate-invalid-toscaDefinitions.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_ENTRY.getMessage(TOSCA_DEFINITIONS_VERSION.getKey()))); + } + + @Test + public void testProcessInvalidEntryTopologyTemplate() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ToscaTemplate-invalidEntry-topologyTemplate.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_ENTRY.getMessage(TOPOLOGY_TEMPLATE.getKey()))); + } + + @Test + public void testProcessInvalidEntryPolicies() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ToscaTemplate-invalidEntry-policies.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_ENTRY.getMessage(POLICIES.getKey()))); + } + + @Test + public void testProcessInvalidPolicy() throws IOException { + ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalidPolicy1.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_POLICY.getMessage())); + + try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalidPolicy2.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_POLICY.getMessage())); + } + + @Test + public void testProcessInvalidEntryProperties() throws IOException { + final ProcessedTemplate processedTemplate; + try (final FileInputStream fileInputStream = + readFileAsStream("ToscaTemplate-invalidEntry-properties.json")) { + processedTemplate = toscaTemplateProcessor.process(fileInputStream); + } + assertProcessedTemplate(processedTemplate, false, + List.of(INVALID_ENTRY.getMessage(PROPERTIES.getKey()))); + } + + + private void assertProcessedTemplate(final ProcessedTemplate process, boolean isValid, + final List expectedErrorList) { + assertThat("Template should be valid", process.isValid(), is(isValid)); + if (isValid || expectedErrorList == null) { + return; + } + assertThat("Should contains the expected quantity of errors", + process.getErrorSet().size(), is(expectedErrorList.size())); + expectedErrorList + .forEach(errorMsg -> assertThat("Should contains a specific error message", process.getErrorSet(), + contains(errorMsg))); + } + + private FileInputStream readFileAsStream(final String fileName) throws FileNotFoundException { + final Path path = Paths.get(testResourcesPath.toString(), fileName); + return new FileInputStream(path.toFile()); + } + + private String readFileAsString(final String fileName) throws IOException { + final Path path = Paths.get(testResourcesPath.toString(), fileName); + return Files.readString(path); + } + +} \ No newline at end of file diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java new file mode 100644 index 0000000..ab9445e --- /dev/null +++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java @@ -0,0 +1,71 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling.plugin.upload; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; +import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey; + +public class UploadPluginClientTest { + + private UploadPluginClient uploadPluginClient; + + @Mock + private Client client; + + private static final String url = "aUrl"; + + /** + * Init the mocks and system properties. + */ + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), url); + final UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters(); + uploadPluginClient = new UploadPluginClient(client, uploadPluginConfigParameters); + } + + @Test + public void upload() { + final Builder mockBuilder = mock(Builder.class); + final WebTarget mockWebTarget = mock(WebTarget.class); + final Response mockResponse = mock(Response.class); + doReturn(mockWebTarget).when(client).target(url); + doReturn(mockBuilder).when(mockWebTarget).request(MediaType.APPLICATION_JSON); + when(mockBuilder.post(any())).thenReturn(mockResponse); + final Response actualResponse = uploadPluginClient.upload(new UploadPolicyRequestDto()); + assertEquals(mockResponse, actualResponse); + } +} \ No newline at end of file -- cgit 1.2.3-korg