diff options
author | Bartosz Gardziejewski <bartosz.gardziejewski@nokia.com> | 2021-05-06 10:14:57 +0200 |
---|---|---|
committer | Bartosz Gardziejewski <bartosz.gardziejewski@nokia.com> | 2021-05-06 10:52:21 +0200 |
commit | 0fce7537299e6af0d2b1fdb1d5c01654ce9573c0 (patch) | |
tree | eb7e726f921fe96738443be684bc77e05f6d76c5 /dictionaryvalidation/src/test/java/org | |
parent | 1ff8bc0e7475934c1ad463571444d7b46c7b5761 (diff) |
Rename PM_Dictionary_Validator to Dictionary_Validatoristanbul
Signed-off-by: Bartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Change-Id: Icb65e6f832804aa4a958e530422d35e079ffe3c1
Issue-ID: VNFSDK-769
Diffstat (limited to 'dictionaryvalidation/src/test/java/org')
18 files changed, 1870 insertions, 0 deletions
diff --git a/dictionaryvalidation/src/test/java/org/onap/functional/DictionaryValidateRuleFunctionalTest.java b/dictionaryvalidation/src/test/java/org/onap/functional/DictionaryValidateRuleFunctionalTest.java new file mode 100644 index 0000000..2d2c542 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/functional/DictionaryValidateRuleFunctionalTest.java @@ -0,0 +1,178 @@ +/* + * Copyright 2020 Nokia + * <p> + * 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 + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> + * 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. + */ + +package org.onap.functional; + +import org.junit.Test; +import org.onap.functional.util.OnapCliWrapper; +import org.onap.validation.rule.DictionaryValidate; +import org.onap.validation.rule.DictionaryValidateResponse; + +import java.net.URISyntaxException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.functional.util.ValidationUtility.OPERATION_STATUS_FAILED; +import static org.onap.functional.util.ValidationUtility.OPERATION_STATUS_PASS; +import static org.onap.functional.util.ValidationUtility.getCliCommandValidationResult; +import static org.onap.functional.util.ValidationUtility.verifyThatOperationFinishedWithError; +import static org.onap.functional.util.ValidationUtility.verifyThatOperationFinishedWithoutAnyError; + + +public class DictionaryValidateRuleFunctionalTest { + + + private static final String YAML_SCHEMA_SIMPLE_VALID_SCHEMA_YAML = "yaml_schema/Simple_Valid_Schema.yaml"; + private static final String YAML_CUSTOM_SCHEMA_SIMPLE_VALID_SCHEMA_YAML = "yaml_schema/Custom_Valid_Dictionary.yaml"; + private static final String YAML_CUSTOM_SCHEMA_SIMPLE_INVALID_SCHEMA_YAML = "yaml_schema/Custom_Invalid_Dictionary.yaml"; + private static final String NO_ERRORS = "[]"; + private static final String YAML_SCHEMA_PM_DICTIONARY_YAML = "yaml_schema/PM_Dictionary.yaml"; + private static final String PATH_TO_NON_EXITING_FILE_YAML = "path/to/nonExitingFile.yaml"; + private static final String NOT_YAML_FILE_TXT = "Not_Yaml_File.txt"; + + @Test + public void shouldSuccessfullyValidatePMDictionaryYamlFile() throws URISyntaxException { + // given + OnapCliWrapper cli = new OnapCliWrapper(createPnfValidationRequestInfo(YAML_SCHEMA_SIMPLE_VALID_SCHEMA_YAML)); + + // when + cli.handle(); + + // then + final DictionaryValidateResponse result = getCliCommandValidationResult(cli, DictionaryValidateResponse.class); + + assertThat(result.getFile()).contains(YAML_SCHEMA_SIMPLE_VALID_SCHEMA_YAML); + assertThat(result.getPlatform()).contains(DictionaryValidateResponse.PLATFORM_VTP_1_0); + assertThat(result.getContact()).contains(DictionaryValidateResponse.ONAP_DISCUSS_LISTS_ONAP_ORG); + assertThat(result.getCriteria()).isEqualTo(OPERATION_STATUS_PASS); + assertThat(result.getErrors()).isEqualTo(NO_ERRORS); + verifyThatOperationFinishedWithoutAnyError(cli); + } + + @Test + public void shouldSuccessfullyValidateCustomDictionaryYamlFile() throws URISyntaxException { + // given + OnapCliWrapper cli = new OnapCliWrapper(createPnfValidationRequestInfo(YAML_CUSTOM_SCHEMA_SIMPLE_VALID_SCHEMA_YAML)); + + // when + cli.handle(); + + // then + final DictionaryValidateResponse result = getCliCommandValidationResult(cli, DictionaryValidateResponse.class); + + assertThat(result.getFile()).contains(YAML_CUSTOM_SCHEMA_SIMPLE_VALID_SCHEMA_YAML); + assertThat(result.getPlatform()).contains(DictionaryValidateResponse.PLATFORM_VTP_1_0); + assertThat(result.getContact()).contains(DictionaryValidateResponse.ONAP_DISCUSS_LISTS_ONAP_ORG); + assertThat(result.getCriteria()).isEqualTo(OPERATION_STATUS_PASS); + verifyThatOperationFinishedWithoutAnyError(cli); + } + + @Test + public void shouldFailWhileValidatingCustomDictionaryYamlFileWithEerror() throws URISyntaxException { + // given + OnapCliWrapper cli = new OnapCliWrapper(createPnfValidationRequestInfo(YAML_CUSTOM_SCHEMA_SIMPLE_INVALID_SCHEMA_YAML)); + + // when + cli.handle(); + + // then + final DictionaryValidateResponse result = getCliCommandValidationResult(cli, DictionaryValidateResponse.class); + + assertThat(result.getFile()).contains(YAML_CUSTOM_SCHEMA_SIMPLE_INVALID_SCHEMA_YAML); + assertThat(result.getPlatform()).contains(DictionaryValidateResponse.PLATFORM_VTP_1_0); + assertThat(result.getContact()).contains(DictionaryValidateResponse.ONAP_DISCUSS_LISTS_ONAP_ORG); + assertThat(result.getCriteria()).isEqualTo(OPERATION_STATUS_FAILED); + final String errors = result.getErrors(); + assertThat(errors).contains( + "Value(s) is/are not in array of accepted values.", + "accepted value(s): [X, Y, Z]", + "accepted value(s): [3, 30, 33]", + "Key not found: field2" + ); + verifyThatOperationFinishedWithoutAnyError(cli); + } + + @Test + public void shouldFailsWhenPMDictionaryYamlFileHasSomeErrors() throws URISyntaxException { + // given + OnapCliWrapper cli = new OnapCliWrapper(createPnfValidationRequestInfo(YAML_SCHEMA_PM_DICTIONARY_YAML)); + + // when + cli.handle(); + + // then + final DictionaryValidateResponse result = getCliCommandValidationResult(cli, DictionaryValidateResponse.class); + + assertThat(result.getFile()).contains(YAML_SCHEMA_PM_DICTIONARY_YAML); + assertThat(result.getPlatform()).contains(DictionaryValidateResponse.PLATFORM_VTP_1_0); + assertThat(result.getContact()).contains(DictionaryValidateResponse.ONAP_DISCUSS_LISTS_ONAP_ORG); + assertThat(result.getCriteria()).isEqualTo(OPERATION_STATUS_FAILED); + final String errors = result.getErrors(); + assertThat(errors).contains( + "Value(s) is/are not in array of accepted values.", + "accepted value(s): [float, uint32, uint64]", + "Key not found: measChangeType", + "accepted value(s): [X, Y, Z]" + ); + verifyThatOperationFinishedWithoutAnyError(cli); + } + + @Test + public void shouldReportAnErrorWhenYamlFileDoesNotExist() { + // given + OnapCliWrapper cli = new OnapCliWrapper(new String[]{PATH_TO_NON_EXITING_FILE_YAML}); + + // when + cli.handle(); + + verifyThatOperationFinishedWithError(cli); + } + + + @Test + public void shouldReportThatValidationFailedWithInternalError() throws URISyntaxException { + // given + OnapCliWrapper cli = new OnapCliWrapper(createPnfValidationRequestInfo(NOT_YAML_FILE_TXT)); + + // when + cli.handle(); + + // then + final DictionaryValidateResponse result = getCliCommandValidationResult(cli, DictionaryValidateResponse.class); + + assertThat(result.getFile()).contains(NOT_YAML_FILE_TXT); + assertThat(result.getPlatform()).contains(DictionaryValidateResponse.PLATFORM_VTP_1_0); + assertThat(result.getContact()).contains(DictionaryValidateResponse.ONAP_DISCUSS_LISTS_ONAP_ORG); + assertThat(result.getCriteria()).isEqualTo(OPERATION_STATUS_FAILED); + assertThat(result.getErrors()).contains("Provided yaml file has invalid structure!"); + verifyThatOperationFinishedWithoutAnyError(cli); + } + + + private String[] createPnfValidationRequestInfo(String yamlPath) throws URISyntaxException { + return new String[]{ + "--product", "onap-honolulu", + "dictionary-validate", + "--format", "json", + "--yaml", absoluteFilePath(yamlPath) + }; + } + + + public static String absoluteFilePath(String relativeFilePath) throws URISyntaxException { + return DictionaryValidate.class.getClassLoader().getResource(relativeFilePath) + .toURI().getPath(); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/functional/util/OnapCliWrapper.java b/dictionaryvalidation/src/test/java/org/onap/functional/util/OnapCliWrapper.java new file mode 100644 index 0000000..347a7bb --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/functional/util/OnapCliWrapper.java @@ -0,0 +1,42 @@ +/* + * Copyright 2020 Nokia + * <p> + * 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 + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> + * 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. + */ + +package org.onap.functional.util; + + +import org.onap.cli.fw.cmd.OnapCommand; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.output.OnapCommandResult; +import org.onap.cli.main.OnapCli; + +public class OnapCliWrapper extends OnapCli { + + private OnapCommandResult commandResult; + + public OnapCliWrapper(String[] args) { + super(args); + } + + @Override + public void handleTracking(OnapCommand cmd) throws OnapCommandException { + super.handleTracking(cmd); + this.commandResult = cmd.getResult(); + } + + public OnapCommandResult getCommandResult() { + return this.commandResult; + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/functional/util/ValidationUtility.java b/dictionaryvalidation/src/test/java/org/onap/functional/util/ValidationUtility.java new file mode 100644 index 0000000..3a497f4 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/functional/util/ValidationUtility.java @@ -0,0 +1,49 @@ +/* + * Copyright 2020 Nokia + * <p> + * 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 + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> + * 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. + */ + +package org.onap.functional.util; + +import com.google.gson.Gson; +import org.onap.cli.fw.output.OnapCommandResult; + + +import static org.assertj.core.api.Assertions.assertThat; + + +public final class ValidationUtility { + + private static final int NO_ERROR_CODE = 0; + public static final int ERROR_CODE = 1; + + private ValidationUtility(){} + + public static final String OPERATION_STATUS_PASS = "PASS"; + public static final String OPERATION_STATUS_FAILED = "FAILED"; + + public static <T> T getCliCommandValidationResult(OnapCliWrapper cli, Class<T> clazz) { + final OnapCommandResult onapCommandResult = cli.getCommandResult(); + final String json = onapCommandResult.getOutput().toString(); + return new Gson().fromJson(json, clazz); + } + + public static void verifyThatOperationFinishedWithoutAnyError(OnapCliWrapper cli) { + assertThat(cli.getExitCode()).isEqualTo(NO_ERROR_CODE); + } + + public static void verifyThatOperationFinishedWithError(OnapCliWrapper cli) { + assertThat(cli.getExitCode()).isEqualTo(ERROR_CODE); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/cli/MainCITest.java b/dictionaryvalidation/src/test/java/org/onap/validation/cli/MainCITest.java new file mode 100644 index 0000000..307d388 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/cli/MainCITest.java @@ -0,0 +1,144 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.cli; + + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.validation.cli.command.validate.OutputFilePathGenerator; +import org.onap.validation.cli.command.validate.ResponseModel; +import org.onap.validation.cli.command.validate.ResponseStorage; +import org.onap.validation.cli.core.Cli; +import org.onap.validation.cli.core.CommandException; +import org.onap.validation.cli.core.Console; +import org.onap.validation.cli.command.validate.ToResponseModelConverter; +import org.onap.validation.yaml.YamlLoadingUtils; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class MainCITest { + + public static final int JSON_RESPONSE_INDEX = 3; + public static final int OPERATION_INFO_MSG_INDEX = 5; + public static final int NO_ERROR = 0; + @Mock + private Console console; + @Mock + private ResponseStorage responseStorage; + private final OutputFilePathGenerator filePathGenerator = new OutputFilePathGenerator(); + + @Test + void shouldReportThatPathToFileWasNotProvided() { + // when + final int statusCode = Main.run(new String[0], console, responseStorage); + + // then + assertThat(statusCode).isEqualTo(Cli.INTERNAL_ERROR_STATUS_CODE); + final ArgumentCaptor<CommandException> exceptionCaptor = ArgumentCaptor.forClass(CommandException.class); + verify(console).error(exceptionCaptor.capture()); + verify(console).error(Cli.APPLICATION_INTERNAL_ERROR_MSG); + assertThat(exceptionCaptor.getValue().getMessage()).isEqualTo("Command argument is missing: provide a path to file"); + + } + + @Test + void shouldReportThatFileDoseNotExist() throws IOException { + // when + final String pathToYaml = "/path/to/nonExisting.yaml"; + final int statusCode = Main.run(new String[]{pathToYaml}, console, new ResponseStorage()); + + // then + assertThat(statusCode).isEqualTo(Cli.INTERNAL_ERROR_STATUS_CODE); + final ArgumentCaptor<CommandException> exceptionCaptor = ArgumentCaptor.forClass(CommandException.class); + verify(console).error(exceptionCaptor.capture()); + verify(console).error(Cli.APPLICATION_INTERNAL_ERROR_MSG); + assertThat(exceptionCaptor.getValue().getMessage()).isEqualTo("File '/path/to/nonExisting.yaml' does not exist!"); + verify(responseStorage, never()).store(eq(Path.of(pathToYaml)), anyString()); + } + + @Test + void shouldReportThatFileIsBroken() throws IOException { + // when + final String pathToFile = YamlLoadingUtils.getUrlForGivenPath("Not_Yaml_File.txt").getPath(); + final int statusCode = Main.run(new String[]{pathToFile}, console, new ResponseStorage()); + + // then + assertThat(statusCode).isEqualTo(Cli.INTERNAL_ERROR_STATUS_CODE); + final ArgumentCaptor<CommandException> exceptionCaptor = ArgumentCaptor.forClass(CommandException.class); + verify(console).error(exceptionCaptor.capture()); + verify(console).error(Cli.APPLICATION_INTERNAL_ERROR_MSG); + assertThat(exceptionCaptor.getValue().getMessage()).isEqualTo("Provided yaml file has invalid structure!"); + verify(responseStorage, never()).store(eq(Path.of(pathToFile)), anyString()); + } + + @Test + void shouldValidateProperYamlFile() throws IOException { + // when + final String path = YamlLoadingUtils.getUrlForGivenPath(YamlLoadingUtils.PATH_TO_SIMPLE_VALID_SCHEMA).getPath(); + final int statusCode = Main.run(new String[]{path}, console, responseStorage); + + // then + assertThat(statusCode).isEqualTo(Cli.PASS_STATUS_CODE); + assertThatResponseWasLoggedAtConsole( + path, + ResponseModel.ResponseStatus.PASS, + NO_ERROR + ); + } + + @Test + void shouldValidateYamlWithErrors() throws IOException { + // when + final String path = YamlLoadingUtils.getUrlForGivenPath(YamlLoadingUtils.PATH_TO_YAML_WITH_WRONG_VALUES).getPath(); + final int statusCode = Main.run(new String[]{path}, console, responseStorage); + + // then + assertThat(statusCode).isEqualTo(Cli.FAILED_STATUS_CODE); + assertThatResponseWasLoggedAtConsole( + path, + ResponseModel.ResponseStatus.FAILED, + 4 + ); + } + + private void assertThatResponseWasLoggedAtConsole(String pathToFile, ResponseModel.ResponseStatus responseStatus, int expectedErrors) throws IOException { + ArgumentCaptor<String> consoleInfoCaptor = ArgumentCaptor.forClass(String.class); + verify(console, times(6)).info(consoleInfoCaptor.capture()); + final List<String> allValues = consoleInfoCaptor.getAllValues(); + final String json = allValues.get(JSON_RESPONSE_INDEX); + final ResponseModel responseModel = ToResponseModelConverter.toModel(json); + assertThat(responseModel.getFile()).isEqualTo(pathToFile); + assertThat(responseModel.getStatus()).isEqualTo(responseStatus); + assertThat(responseModel.getErrors()).hasSize(expectedErrors); + assertThat(consoleInfoCaptor.getAllValues().get(OPERATION_INFO_MSG_INDEX)).isEqualTo(Cli.APPLICATION_EXIT_SUCCESSFULLY_MSG); + verify(responseStorage).store(eq(filePathGenerator.responsePathFor(Path.of(pathToFile))), eq(json)); + } + +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/OutputFilePathGeneratorTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/OutputFilePathGeneratorTest.java new file mode 100644 index 0000000..b4d68b4 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/OutputFilePathGeneratorTest.java @@ -0,0 +1,43 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.cli.command.validate; + +import org.junit.jupiter.api.Test; + +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; + + +class OutputFilePathGeneratorTest { + + private final OutputFilePathGenerator filePathGenerator = new OutputFilePathGenerator(); + + @Test + void shouldReturnPathToFileWithResponse() { + // given + final Path pathToYaml = Path.of("/some/path/PMDictionary.yaml"); + final Path expected = Path.of("/some/path/PMDictionary-validation-results.json"); + + // when + final Path actual = filePathGenerator.responsePathFor(pathToYaml); + + // then + assertThat(actual).isEqualTo(expected); + } + +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java new file mode 100644 index 0000000..06a15bb --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java @@ -0,0 +1,70 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.cli.command.validate; + +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.error.YamlDocumentValidationError; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.validation.cli.command.validate.ToResponseModelConverter.toModel; + + +class ToJsonConverterTest { + + private static final String PATH_TO_TEST_YAML = "/path/to/test.yaml"; + private final ToJsonConverter toJsonConverter = new ToJsonConverter(); + + @Test + void shouldConvertEmptyArray() { + // given + final ResponseModel responseModel = new ResponseModel(PATH_TO_TEST_YAML, + ResponseModel.ResponseStatus.PASS, + List.of()); + + // when + String json = toJsonConverter.convert(responseModel); + + // then + ResponseModel actual = toModel(json); + assertThat(actual.getFile()).isEqualTo(PATH_TO_TEST_YAML); + assertThat(actual.getStatus()).isEqualTo(ResponseModel.ResponseStatus.PASS); + assertThat(actual.getErrors()).isEmpty(); + } + + + @Test + void shouldConvertListOfErrors() { + // given + final ResponseModel responseModel = new ResponseModel(PATH_TO_TEST_YAML, + ResponseModel.ResponseStatus.FAILED, + List.of( + new YamlDocumentValidationError(1, PATH_TO_TEST_YAML, "error1"), + new YamlDocumentValidationError(2, PATH_TO_TEST_YAML, "error2"))); + + // when + String json = toJsonConverter.convert(responseModel); + + // then + + ResponseModel actual = toModel(json); + assertThat(actual.getFile()).isEqualTo(PATH_TO_TEST_YAML); + assertThat(actual.getStatus()).isEqualTo(ResponseModel.ResponseStatus.FAILED); + assertThat(actual.getErrors()).hasSize(2); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ValidateYamlCommandTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ValidateYamlCommandTest.java new file mode 100644 index 0000000..9d651ad --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ValidateYamlCommandTest.java @@ -0,0 +1,96 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.cli.command.validate; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.validation.cli.core.CommandException; +import org.onap.validation.cli.core.CommandResponse; +import org.onap.validation.yaml.YamlLoadingUtils; +import org.onap.validation.yaml.util.Args; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.onap.validation.cli.command.validate.ToResponseModelConverter.toModel; + +@ExtendWith(MockitoExtension.class) +class ValidateYamlCommandTest { + + private final ToJsonConverter toJsonConverter = new ToJsonConverter(); + private ValidateDictionaryYamlCommand validateYamlCommand; + + @BeforeEach + void setUp() { + this.validateYamlCommand = new ValidateDictionaryYamlCommand(toJsonConverter); + } + + @Test + void shouldReportAnErrorWhenFileDoesNotExist() { + // given + Args args = new Args(List.of("/invalid/filePath/toValidate.yaml")); + + // when + assertThatThrownBy(() -> validateYamlCommand.execute(args)).hasMessage("File '/invalid/filePath/toValidate.yaml' does not exist!"); + } + + @Test + void shouldReportAnErrorWhenPathToFileWasNotPass() { + // given + Args args = new Args(List.of()); + + // when + assertThatThrownBy(() -> validateYamlCommand.execute(args)).hasMessage("Command argument is missing: provide a path to file"); + } + + @Test + void shouldValidateFileWithoutAnyError() throws CommandException { + // given + final String path = YamlLoadingUtils.getUrlForGivenPath(YamlLoadingUtils.PATH_TO_SIMPLE_VALID_SCHEMA).getPath(); + Args args = new Args(List.of(path)); + + // when + final CommandResponse<String> commandResponse = validateYamlCommand.execute(args); + + // then + assertThat(commandResponse.getCommandStatus()).isEqualTo(CommandResponse.CommandStatus.PASS); + ResponseModel actual = toModel(commandResponse.getResult()); + assertThat(actual.getFile()).isEqualTo(path); + assertThat(actual.getStatus()).isEqualTo(ResponseModel.ResponseStatus.PASS); + assertThat(actual.getErrors()).isEmpty(); + } + + @Test + void shouldReportThatFileHasSomeErrors() throws CommandException { + // given + final String path = YamlLoadingUtils.getUrlForGivenPath(YamlLoadingUtils.PATH_TO_YAML_WITH_WRONG_VALUES).getPath(); + Args args = new Args(List.of(path)); + + // when + final CommandResponse<String> commandResponse = validateYamlCommand.execute(args); + + // then + assertThat(commandResponse.getCommandStatus()).isEqualTo(CommandResponse.CommandStatus.FAILED); + ResponseModel actual = toModel(commandResponse.getResult()); + assertThat(actual.getFile()).isEqualTo(path); + assertThat(actual.getStatus()).isEqualTo(ResponseModel.ResponseStatus.FAILED); + assertThat(actual.getErrors()).hasSize(4); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/cli/core/CliTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/cli/core/CliTest.java new file mode 100644 index 0000000..c8ad629 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/cli/core/CliTest.java @@ -0,0 +1,101 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.cli.core; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.validation.cli.command.validate.ResponseStorage; +import org.onap.validation.yaml.util.Args; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + + +@ExtendWith(MockitoExtension.class) +class CliTest { + @Mock + private Console console; + + @Mock + private ResponseStorage responseStorage; + + @Mock + private Command<String> validationCommand; + + private Cli<String> cli; + + @BeforeEach + void setUp() { + cli = new Cli<>(console, responseStorage); + } + + @Test + void shouldExecuteCommandWithoutAnyError() throws CommandException { + + // given + Args args = new Args(List.of()); + when(validationCommand.execute(args)).thenReturn( + new CommandResponse<>("{ 'errors': [] }", CommandResponse.CommandStatus.PASS) + ); + + // when + final int exitCode = cli.run(args, validationCommand); + + // then + assertThat(exitCode).isEqualTo(Cli.PASS_STATUS_CODE); + verify(console).info("{ 'errors': [] }"); + } + + @Test + void shouldHandleErrorReportedByCommand() throws CommandException { + + // given + Args args = new Args(List.of()); + final CommandException commandException = new CommandException("It should be reported"); + Mockito.doThrow(commandException).when(validationCommand).execute(args); + + // when + final int exitCode = cli.run(args, validationCommand); + + // then + assertThat(exitCode).isEqualTo(Cli.INTERNAL_ERROR_STATUS_CODE); + verify(console).error(commandException); + } + + @Test + void shouldHandleRuntimeException() throws CommandException { + + // given + Args args = new Args(List.of()); + final RuntimeException commandException = new RuntimeException(); + Mockito.doThrow(commandException).when(validationCommand).execute(args); + + // when + final int exitCode = cli.run(args, validationCommand); + + // then + assertThat(exitCode).isEqualTo(Cli.INTERNAL_ERROR_STATUS_CODE); + verify(console).error(commandException); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java new file mode 100644 index 0000000..ff4e55b --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java @@ -0,0 +1,164 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.yaml; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.error.YamlDocumentValidationError; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.yaml.snakeyaml.parser.ParserException; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.onap.validation.yaml.YamlLoadingUtils.PATH_TO_MULTI_DOCUMENT_INVALID_YAML; +import static org.onap.validation.yaml.YamlLoadingUtils.PATH_TO_VALID_JSON_STYLE_YAML; +import static org.onap.validation.yaml.YamlLoadingUtils.PATH_TO_YAML_WITH_WRONG_VALUES; +import static org.onap.validation.yaml.YamlLoadingUtils.readFile; + +class YamlContentValidatorTest { + + final YamlContentValidator yamlContentValidator = new YamlContentValidator(); + + @Nested + class FromStringPathValidator { + @Test + void shouldReturnCorrectErrorsWhenGivenPathToValidPmDictionaryFile() throws YamlProcessingException { + // given + String path = getFullPathForGivenResources(PATH_TO_YAML_WITH_WRONG_VALUES); + + // when + List<YamlDocumentValidationError> validationErrors = new YamlContentValidator().validate(path); + + // then + assertValidationReturnedExpectedErrors(validationErrors); + } + + @Test + void shouldReturnCorrectErrorsWhenGivenPathToValidJsonStylePmDictionaryFile() throws YamlProcessingException { + // given + String path = getFullPathForGivenResources(PATH_TO_VALID_JSON_STYLE_YAML); + + // when + List<YamlDocumentValidationError> validationErrors = new YamlContentValidator().validate(path); + + // then + assertValidationReturnedExpectedErrors(validationErrors); + } + + @Test + void shouldThrowErrorWhenGivenPathToInvalidPmDictionaryFile() { + // given + String path = getFullPathForGivenResources(PATH_TO_MULTI_DOCUMENT_INVALID_YAML); + + //when then + assertThatThrownBy(() -> yamlContentValidator.validate(path)) + .isInstanceOf(ParserException.class) + .hasMessageContaining("expected the node content, but found '<document end>'"); + } + + @Test + void shouldThrowErrorWhenGivenInvalidPath() { + // given + String path = "invalid/path/to/pm_dictionary"; + + //when then + assertThatThrownBy(() -> yamlContentValidator.validate(path)) + .isInstanceOf(YamlProcessingException.class) + .hasMessageContaining("Dictionary YAML file is empty"); + } + } + + @Nested + class FromByteArrayValidator { + @Test + void shouldReturnCorrectErrorsWhenGivenPmDictionaryFileWithErrors() throws YamlProcessingException, IOException { + // given + byte[] yaml = readFile(PATH_TO_YAML_WITH_WRONG_VALUES); + + // when + List<YamlDocumentValidationError> validationErrors = new YamlContentValidator().validate(yaml); + + // then + assertValidationReturnedExpectedErrors(validationErrors); + } + + @Test + void shouldReturnCorrectErrorsWhenGivenValidJsonStylePmDictionary() throws YamlProcessingException, IOException { + // given + byte[] yaml = readFile(PATH_TO_VALID_JSON_STYLE_YAML); + + // when + List<YamlDocumentValidationError> validationErrors = new YamlContentValidator().validate(yaml); + + // then + assertValidationReturnedExpectedErrors(validationErrors); + } + + @Test + void shouldThrowErrorWhenGivenInvalidPmDictionary() throws IOException { + // given + byte[] yaml = readFile(PATH_TO_MULTI_DOCUMENT_INVALID_YAML); + + //when then + assertThatThrownBy(() -> new YamlContentValidator().validate(yaml)) + .isInstanceOf(ParserException.class) + .hasMessageContaining("expected the node content, but found '<document end>'"); + } + + @Test + void shouldThrowErrorWhenGivenEmptyPmDictionary() { + //when then + assertThatThrownBy(() -> new YamlContentValidator().validate(new byte[0])) + .isInstanceOf(YamlProcessingException.class) + .hasMessageContaining("Dictionary YAML file is empty"); + } + } + + private void assertValidationReturnedExpectedErrors(List<YamlDocumentValidationError> validationErrors) { + assertThat(validationErrors) + .isNotNull() + .hasSize(4) + .usingRecursiveFieldByFieldElementComparator() + .containsAll( + List.of( + new YamlDocumentValidationError(1, + "/pmMetaData/pmFields/measResultType", + "Value(s) is/are not in array of accepted values.\n" + + " value(s): integer\n" + + " accepted value(s): [float, uint32, uint64]"), + new YamlDocumentValidationError(1, + "/pmMetaData/pmFields/", + "Key not found: measChangeType"), + new YamlDocumentValidationError(2, + "/pmMetaData/pmFields/", + "Key not found: measChangeType"), + new YamlDocumentValidationError(3, + "/pmMetaData/pmFields/measAdditionalFields/vendorField1", + "Value(s) is/are not in array of accepted values.\n" + + " value(s): [Z, A]\n" + + " accepted value(s): [X, Y, Z]") + ) + ); + } + + private String getFullPathForGivenResources(String pathToValidYaml) { + return this.getClass().getClassLoader().getResource(pathToValidYaml).getPath(); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java new file mode 100644 index 0000000..3e1f601 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java @@ -0,0 +1,148 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.yaml; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.model.YamlDocument; +import org.onap.validation.yaml.model.YamlDocumentFactory; +import org.yaml.snakeyaml.parser.ParserException; +import org.yaml.snakeyaml.scanner.ScannerException; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class YamlLoaderTest { + private static final int EXPECTED_NUMBER_OF_DOCUMENTS = 5; + private static final String LETTER_S_WITH_ASCII_CODE = "s(115)"; + + @Nested + class FromUrlLoader { + @Test + void shouldLoadAllDocumentsFromYamlFile() throws YamlDocumentFactory.YamlDocumentParsingException { + // when + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFile(); + + // then + assertThat(documents).hasSize(EXPECTED_NUMBER_OF_DOCUMENTS); + } + + @Test + void shouldLoadAllDocumentsFromJsonStyleYamlFile() throws YamlDocumentFactory.YamlDocumentParsingException { + // when + List<YamlDocument> documents = YamlLoadingUtils.loadValidJsonStyleMultiDocumentYamlFile(); + + // then + assertThat(documents).hasSize(EXPECTED_NUMBER_OF_DOCUMENTS); + } + + @Test + void shouldThrowExceptionWhenLoadingDocumentsFromInvalidYamlFile() { + // when then + assertThatThrownBy(YamlLoadingUtils::tryToLoadMultiDocumentInvalidYamlFile) + .isInstanceOf(ParserException.class) + .hasMessageContaining("expected the node content, but found '<document end>'"); + } + + @Test + void shouldThrowExceptionWhenLoadingInvalidYamlFileWithIncorrectKeyMapping() { + // when then + assertThatThrownBy(YamlLoadingUtils::tryToLoadInvalidYamlFileWithIncorrectKeyMapping) + .isInstanceOf(ScannerException.class) + .hasMessageContaining("mapping values are not allowed here"); + } + + @Test + void shouldThrowExceptionWhenLoadingInvalidYamlFileWithUnknownEscapeCharacter() { + // when then + assertThatThrownBy(YamlLoadingUtils::tryToLoadInvalidYamlFileWithUnknownEscapeCharacter) + .isInstanceOf(ScannerException.class) + .hasMessageContaining("found unknown escape character " + LETTER_S_WITH_ASCII_CODE); + } + } + + @Nested + class FromStringPathLoader { + @Test + void shouldLoadAllDocumentsFromYamlFileUsingPathInString() throws YamlProcessingException { + // when + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFileUsingStringPath(); + + // then + assertThat(documents).hasSize(EXPECTED_NUMBER_OF_DOCUMENTS); + } + + @Test + void shouldThrowExceptionWhenLoadingDocumentsFromInvalidYamlFileUsingPathInString() { + // when then + assertThatThrownBy(YamlLoadingUtils::tryToLoadMultiDocumentInvalidYamlFileUsingStringPath) + .isInstanceOf(ParserException.class) + .hasMessageContaining("expected the node content, but found '<document end>'"); + } + } + + @Nested + class FromByteArrayLoader { + private final YamlLoader YAML_LOADER = new YamlLoader(new YamlDocumentFactory()); + + @Test + void shouldLoadAllDocumentsFromYamlFile() throws YamlDocumentFactory.YamlDocumentParsingException, IOException { + // when + List<YamlDocument> documents = YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_YAML_WITH_WRONG_VALUES)); + + // then + assertThat(documents).hasSize(EXPECTED_NUMBER_OF_DOCUMENTS); + } + + @Test + void shouldLoadAllDocumentsFromJsonStyleYamlFile() throws YamlDocumentFactory.YamlDocumentParsingException, IOException { + // when + List<YamlDocument> documents = YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_VALID_JSON_STYLE_YAML)); + + // then + assertThat(documents).hasSize(EXPECTED_NUMBER_OF_DOCUMENTS); + } + + @Test + void shouldThrowExceptionWhenLoadingDocumentsFromInvalidYamlFile() { + // when then + assertThatThrownBy(() -> YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_MULTI_DOCUMENT_INVALID_YAML))) + .isInstanceOf(ParserException.class) + .hasMessageContaining("expected the node content, but found '<document end>'"); + } + + @Test + void shouldThrowExceptionWhenLoadingInvalidYamlFileWithIncorrectKeyMapping() { + // when then + assertThatThrownBy(() -> YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_INVALID_YAML_WITH_INCORRECT_KEY_MAPPING))) + .isInstanceOf(ScannerException.class) + .hasMessageContaining("mapping values are not allowed here"); + } + + @Test + void shouldThrowExceptionWhenLoadingInvalidYamlFileWithUnknownEscapeCharacter() { + // when then + assertThatThrownBy(() -> YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_INVALID_YAML_WITH_UNKNOWN_ESCAPE_CHARACTER))) + .isInstanceOf(ScannerException.class) + .hasMessageContaining("found unknown escape character " + LETTER_S_WITH_ASCII_CODE); + } + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java new file mode 100644 index 0000000..dc1ce3b --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java @@ -0,0 +1,104 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.yaml; + +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.model.YamlDocument; +import org.onap.validation.yaml.model.YamlDocumentFactory; + +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.onap.validation.yaml.model.YamlDocumentFactory.YamlDocumentParsingException; + +public final class YamlLoadingUtils { + + public static final YamlLoader YAML_LOADER = new YamlLoader(new YamlDocumentFactory()); + + private YamlLoadingUtils() { + } + + public static final int VALID_YAML_DOCUMENT_INDEX = 4; + public static final int YAML_DOCUMENT_WITH_WRONG_VALUE_IN_ARRAY_INDEX = 3; + public static final int YAML_DOCUMENT_WITH_MISSING_FIELD_INDEX = 2; + public static final int YAML_DOCUMENT_WITH_MISSING_FIELD_AND_WRONG_VALUE_INDEX = 1; + public static final String PATH_TO_YAML_WITH_WRONG_VALUES = "yaml_schema/PM_Dictionary.yaml"; + public static final String PATH_TO_VALID_JSON_STYLE_YAML = "yaml_schema/PM_Dictionary_JSON_Style.yaml"; + public static final String PATH_TO_SIMPLE_VALID_SCHEMA = "yaml_schema/Simple_Valid_Schema.yaml"; + public static final String PATH_TO_SIMPLE_VALID_SCHEMA_MULTI_ROOT = "yaml_schema/Simple_Valid_Schema_Multi_Root.yaml"; + public static final String PATH_TO_SIMPLE_INVALID_SCHEMA = "yaml_schema/Simple_Invalid_Schema_Construction.yaml"; + public static final String PATH_TO_SIMPLE_INVALID_SCHEMA_FOR_LAZY_LOADING = "yaml_schema/Simple_Invalid_Schema_LazyLoading.yaml"; + public static final String PATH_TO_MULTI_DOCUMENT_INVALID_YAML = "yaml_schema/Multi_Document_Invalid.yaml"; + public static final String PATH_TO_INVALID_YAML_WITH_INCORRECT_KEY_MAPPING = "yaml_schema/Simple_Invalid_Mapping_Value.yaml"; + public static final String PATH_TO_INVALID_YAML_WITH_UNKNOWN_ESCAPE_CHARACTER = "yaml_schema/Simple_Unknown_Escape_Character.yaml"; + + public static List<YamlDocument> loadValidMultiDocumentYamlFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_YAML_WITH_WRONG_VALUES)); + } + + public static List<YamlDocument> loadValidJsonStyleMultiDocumentYamlFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_VALID_JSON_STYLE_YAML)); + } + + public static List<YamlDocument> loadValidMultiDocumentYamlFileUsingStringPath() throws YamlProcessingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_YAML_WITH_WRONG_VALUES).getPath()); + } + + public static YamlDocument loadSimpleValidYamlSchemaFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_SIMPLE_VALID_SCHEMA)).get(0); + } + + public static YamlDocument loadSimpleInvalidYamlSchemaFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_SIMPLE_INVALID_SCHEMA)).get(0); + } + + public static YamlDocument loadSimpleInvalidYamlSchemaForLazyLoadingFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_SIMPLE_INVALID_SCHEMA_FOR_LAZY_LOADING)).get(0); + } + + public static YamlDocument loadSimpleValidYamlSchemaWithMultiRootFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_SIMPLE_VALID_SCHEMA_MULTI_ROOT)).get(0); + } + + public static List<YamlDocument> tryToLoadMultiDocumentInvalidYamlFile() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_MULTI_DOCUMENT_INVALID_YAML)); + } + + public static List<YamlDocument> tryToLoadMultiDocumentInvalidYamlFileUsingStringPath() throws YamlProcessingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_MULTI_DOCUMENT_INVALID_YAML).getPath()); + } + + public static List<YamlDocument> tryToLoadInvalidYamlFileWithIncorrectKeyMapping() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_INVALID_YAML_WITH_INCORRECT_KEY_MAPPING)); + } + + public static List<YamlDocument> tryToLoadInvalidYamlFileWithUnknownEscapeCharacter() throws YamlDocumentParsingException { + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_INVALID_YAML_WITH_UNKNOWN_ESCAPE_CHARACTER)); + } + + public static byte[] readFile(String path) throws IOException { + String file = getUrlForGivenPath(path).getFile(); + return Files.readAllBytes(Path.of(file)); + } + + public static URL getUrlForGivenPath(String path) { + return YamlLoadingUtils.class.getClassLoader().getResource(path); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlValidatorTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlValidatorTest.java new file mode 100644 index 0000000..3d993f8 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlValidatorTest.java @@ -0,0 +1,115 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ + +package org.onap.validation.yaml; + +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.error.SchemaValidationError; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.model.YamlDocument; +import org.onap.validation.yaml.schema.YamlSchemaFactory; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.validation.yaml.YamlLoadingUtils.VALID_YAML_DOCUMENT_INDEX; +import static org.onap.validation.yaml.YamlLoadingUtils.YAML_DOCUMENT_WITH_MISSING_FIELD_AND_WRONG_VALUE_INDEX; +import static org.onap.validation.yaml.YamlLoadingUtils.YAML_DOCUMENT_WITH_MISSING_FIELD_INDEX; +import static org.onap.validation.yaml.YamlLoadingUtils.YAML_DOCUMENT_WITH_WRONG_VALUE_IN_ARRAY_INDEX; + +class YamlValidatorTest { + + @Test + void shouldCreateValidatorUsingSchemaLoadedFromYamlFileAndValidatedJsonStyleDocumentsFromThatFile() + throws YamlProcessingException { + // given + List<YamlDocument> documents = YamlLoadingUtils.loadValidJsonStyleMultiDocumentYamlFile(); + YamlValidator validator = new YamlValidator(new YamlSchemaFactory().createTreeStructuredYamlSchema(documents.get(0))); + Map<Integer, List<SchemaValidationError>> validationErrors = new HashMap<>(); + + // when + for (int documentIndex = 1; documentIndex < documents.size(); documentIndex++) { + validationErrors.put(documentIndex, validator.validate(documents.get(documentIndex))); + } + + // then + assertValidatorReturnedCorrectErrors(validationErrors); + } + + @Test + void shouldCreateValidatorUsingSchemaLoadedFromYamlFileAndValidatedDocumentsFromThatFile() + throws YamlProcessingException { + // given + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFile(); + YamlValidator validator = new YamlValidator(new YamlSchemaFactory().createTreeStructuredYamlSchema(documents.get(0))); + Map<Integer, List<SchemaValidationError>> validationErrors = new HashMap<>(); + + // when + for (int documentIndex = 1; documentIndex < documents.size(); documentIndex++) { + validationErrors.put(documentIndex, validator.validate(documents.get(documentIndex))); + } + + // then + assertValidatorReturnedCorrectErrors(validationErrors); + } + + private void assertValidatorReturnedCorrectErrors(Map<Integer, List<SchemaValidationError>> validationErrors) { + + SchemaValidationError expectedValidationValueError = + new SchemaValidationError( + "/pmMetaData/pmFields/measResultType", + "Value(s) is/are not in array of accepted values.\n" + + " value(s): integer\n" + + " accepted value(s): [float, uint32, uint64]" + ); + SchemaValidationError expectedValidationKeyError = + new SchemaValidationError( + "/pmMetaData/pmFields/", + "Key not found: measChangeType" + ); + SchemaValidationError expectedValidationValuesInArrayError = + new SchemaValidationError( + "/pmMetaData/pmFields/measAdditionalFields/vendorField1", + "Value(s) is/are not in array of accepted values.\n" + + " value(s): [Z, A]\n" + + " accepted value(s): [X, Y, Z]" + ); + + assertThat(validationErrors) + .hasSize(4) + .containsKeys(1, 2, 3); + assertThat(validationErrors.get(YAML_DOCUMENT_WITH_MISSING_FIELD_AND_WRONG_VALUE_INDEX)) + .hasSize(2) + .usingFieldByFieldElementComparator() + .containsAll(List.of( + expectedValidationValueError, + expectedValidationKeyError + )); + assertThat(validationErrors.get(YAML_DOCUMENT_WITH_MISSING_FIELD_INDEX)) + .hasSize(1) + .usingFieldByFieldElementComparator() + .contains(expectedValidationKeyError); + assertThat(validationErrors.get(YAML_DOCUMENT_WITH_WRONG_VALUE_IN_ARRAY_INDEX)) + .hasSize(1) + .usingFieldByFieldElementComparator() + .contains(expectedValidationValuesInArrayError); + assertThat(validationErrors.get(VALID_YAML_DOCUMENT_INDEX)).isEmpty(); + } + +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/model/YamlDocumentFactoryTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/model/YamlDocumentFactoryTest.java new file mode 100644 index 0000000..d7d1153 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/model/YamlDocumentFactoryTest.java @@ -0,0 +1,130 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ + +package org.onap.validation.yaml.model; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.ThrowableAssert.catchThrowable; +import static org.onap.validation.yaml.model.YamlDocumentFactory.YamlDocumentParsingException; + +class YamlDocumentFactoryTest { + + @Test + void shouldTurnMapOfUnknownKeyTypeToMapWithStringKeysAndBeAbleToReturnStringifyValues() + throws YamlDocumentParsingException { + // given + List<String> testList = List.of("element1", "element11"); + Map<Object, Object> testEmptyMap = Collections.emptyMap(); + Map<Object, Object> inputMap = Map.of( + "test", testList, + 345, "element2", + "test2", "element3", + 2.67, testEmptyMap); + + // when + YamlDocument document = new YamlDocumentFactory().createYamlDocument(inputMap); + + // then + assertYamlDocument(document, inputMap); + } + + @Test + void shouldTurnMapOfUnknownKeyTypeToMapWithStringKeysAndBeAbleToExtractSubStructure() + throws YamlDocumentParsingException { + // given + Map<Object, Object> subStructureMap = Map.of( + "subTest1", "subElement1", + "subTest2", "subElement2"); + Map<Object, Object> inputMap = Map.of( + "test", "element1", + "structure", subStructureMap); + + // when + YamlDocument document = new YamlDocumentFactory().createYamlDocument(inputMap); + + // then + assertYamlDocument(document, inputMap); + } + + @Test + void shouldTurnMapOfUnknownKeyTypeToMapWithStringKeysAndBeAbleToExtractParametersList() + throws YamlDocumentParsingException { + // given + List<String> parametersList = List.of("parameter1", "parameter2"); + Map<Object, Object> inputMap = Map.of( + "test", "element1", + "parameters", parametersList); + + // when + YamlDocument document = new YamlDocumentFactory().createYamlDocument(inputMap); + + // then + assertYamlDocument(document, inputMap); + } + + @Test + void shouldThrowExceptionIfGetSubStructureIsCalledOnList() + throws YamlDocumentParsingException { + // given + List<String> testList = List.of("element1", "element2"); + Map<Object, Object> inputMap = Collections.singletonMap("test", testList); + YamlDocument document = new YamlDocumentFactory().createYamlDocument(inputMap); + + // when + Throwable ex = catchThrowable(() -> document.getSubStructure("test")); + + // then + assertYamlDocumentParsingException(ex, testList); + } + + @Test + void shouldThrowExceptionIfGetSubStructureIsCalledOnString() + throws YamlDocumentParsingException { + // given + Map<Object, Object> inputMap = Collections.singletonMap("test", "testElement"); + YamlDocument document = new YamlDocumentFactory().createYamlDocument(inputMap); + + // when + Throwable ex = catchThrowable(() -> document.getSubStructure("test")); + + // then + assertYamlDocumentParsingException(ex, "testElement"); + } + + private void assertYamlDocument(YamlDocument document, Map<Object, Object> inputMap) { + assertThat(document).isNotNull(); + assertThat(document.getYaml()).containsExactlyEntriesOf(mapKeyToString(inputMap)); + } + + private Map<String, Object> mapKeyToString(Map<Object, Object> inputMap) { + return inputMap.entrySet().stream() + .collect(Collectors.toMap(w -> w.getKey().toString(), Map.Entry::getValue)); + } + + private void assertYamlDocumentParsingException(Throwable ex, Object unparsed) { + assertThat(ex) + .isInstanceOf(YamlDocumentParsingException.class) + .hasMessageContaining(String.format("Fail to parse given objects: %s as yaml document.", unparsed)); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/model/YamlParameterListFactoryTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/model/YamlParameterListFactoryTest.java new file mode 100644 index 0000000..ab6f882 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/model/YamlParameterListFactoryTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ + +package org.onap.validation.yaml.model; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class YamlParameterListFactoryTest { + + @Test + void shouldCreateEmptyParametersList() { + // when + YamlParametersList parametersList = new YamlParameterListFactory().createEmptyYamlParameterList(); + + // then + assertThat(parametersList).isNotNull(); + assertThat(parametersList.getParameters()).isEmpty(); + } + + @Test + void shouldCreateParametersListContainingStringsFromListContainingSimpleTypes() { + // given + List<Object> testList = List.of("test1", 3, 23.45, 'a', "test2"); + + // when + YamlParametersList parametersList = new YamlParameterListFactory().createYamlParameterList(testList); + + // then + assertYamlParametersList(parametersList, testList); + } + + @Test + void shouldCreateParametersListContainingStringsFromListContainingVariousTypes() { + // given + List<Object> testList = List.of("test1", 3, List.of(2, 3, 4), "test2"); + + // when + YamlParametersList parametersList = new YamlParameterListFactory().createYamlParameterList(testList); + + // then + assertYamlParametersList(parametersList, testList); + } + + @Test + void shouldCreateListWithOneStringWhenGivenObjectIsNotList() { + // given + Object testObject = "test"; + + // when + YamlParametersList parametersList = new YamlParameterListFactory().createYamlParameterList(testObject); + + // then + assertYamlParametersList(parametersList, Collections.singletonList(testObject)); + } + + private void assertYamlParametersList(YamlParametersList parametersList, List<Object> testList) { + assertThat(parametersList).isNotNull(); + assertThat(parametersList.getParameters()) + .containsExactly(mapToStrings(testList)); + } + + private String[] mapToStrings(List<Object> elements) { + return elements.stream().map(Object::toString).toArray(String[]::new); + } + +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/process/YamlValidationProcessTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/process/YamlValidationProcessTest.java new file mode 100644 index 0000000..5c9d8e5 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/process/YamlValidationProcessTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ + +package org.onap.validation.yaml.process; + +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.YamlLoadingUtils; +import org.onap.validation.yaml.error.SchemaValidationError; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.model.YamlDocument; +import org.onap.validation.yaml.schema.YamlSchema; +import org.onap.validation.yaml.schema.YamlSchemaFactory; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.onap.validation.yaml.YamlLoadingUtils.VALID_YAML_DOCUMENT_INDEX; +import static org.onap.validation.yaml.YamlLoadingUtils.YAML_DOCUMENT_WITH_MISSING_FIELD_AND_WRONG_VALUE_INDEX; +import static org.onap.validation.yaml.YamlLoadingUtils.YAML_DOCUMENT_WITH_MISSING_FIELD_INDEX; + +class YamlValidationProcessTest { + + @Test + void shouldReturnNoErrorWhenProcessingValidPmDictionaryYaml() + throws YamlProcessingException { + // given + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFile(); + YamlSchema schema = new YamlSchemaFactory().createTreeStructuredYamlSchema(documents.get(0)); + YamlDocument document = documents.get(VALID_YAML_DOCUMENT_INDEX); + + // when + List<SchemaValidationError> errors = new YamlValidationProcess(schema, document).validate(); + + // then + assertThat(errors).isEmpty(); + } + + @Test + void shouldReturnOneErrorWhenProcessingPmDictionaryYamlWithMissingField() + throws YamlProcessingException { + // given + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFile(); + YamlSchema schema = new YamlSchemaFactory().createTreeStructuredYamlSchema(documents.get(0)); + YamlDocument document = documents.get(YAML_DOCUMENT_WITH_MISSING_FIELD_INDEX); + + // when + List<SchemaValidationError> errors = new YamlValidationProcess(schema, document).validate(); + + // then + assertThat(errors).hasSize(1); + } + + @Test + void shouldReturnTwoErrorsWhenProcessingPmDictionaryYamlWithMissingFieldAndIncorrectValue() + throws YamlProcessingException { + // given + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFile(); + YamlSchema schema = new YamlSchemaFactory().createTreeStructuredYamlSchema(documents.get(0)); + YamlDocument document = documents.get(YAML_DOCUMENT_WITH_MISSING_FIELD_AND_WRONG_VALUE_INDEX); + + // when + List<SchemaValidationError> errors = new YamlValidationProcess(schema, document).validate(); + + // then + assertThat(errors).hasSize(2); + } + + @Test + void shouldThrowExceptionWhenProcessingPmDictionaryIsNotValidYaml() + throws YamlProcessingException { + // given + List<YamlDocument> documents = YamlLoadingUtils.loadValidMultiDocumentYamlFile(); + YamlDocument schemaInYaml = YamlLoadingUtils.loadSimpleInvalidYamlSchemaForLazyLoadingFile(); + YamlSchema schema = new YamlSchemaFactory().createTreeStructuredYamlSchema(schemaInYaml); + YamlDocument document = documents.get(VALID_YAML_DOCUMENT_INDEX); + + // when + Throwable ex = catchThrowable(() -> new YamlValidationProcess(schema, document).validate()); + + // then + assertThat(ex) + .isInstanceOf(YamlProcessingException.class) + .hasMessageContaining("Lazy loading failed, due to yaml parsing exception."); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/schema/YamlSchemaFactoryTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/schema/YamlSchemaFactoryTest.java new file mode 100644 index 0000000..efc304c --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/schema/YamlSchemaFactoryTest.java @@ -0,0 +1,115 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ + +package org.onap.validation.yaml.schema; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.YamlLoadingUtils; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.model.YamlDocument; +import org.onap.validation.yaml.schema.node.YamlSchemaNode; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.onap.validation.yaml.model.YamlDocumentFactory.YamlDocumentParsingException; +import static org.onap.validation.yaml.schema.node.YamlSchemaNodeFactory.EMPTY_COMMENT; +import static org.onap.validation.yaml.schema.node.YamlSchemaNodeFactoryTest.assertThatBranchNodeIsValid; +import static org.onap.validation.yaml.schema.node.YamlSchemaNodeFactoryTest.assertThatLeafNodeIsValid; + + +class YamlSchemaFactoryTest { + + @Test + void shouldCreateYamlSchemaFromYamlDocumentWithMultipleRoots() + throws YamlProcessingException { + // given + YamlDocument documents = YamlLoadingUtils.loadSimpleValidYamlSchemaWithMultiRootFile(); + + // when + YamlSchema schema = new YamlSchemaFactory().createTreeStructuredYamlSchema(documents); + + // then + assertThat(schema).isNotNull(); + assertThat(schema.getRootNodes()) + .extracting(YamlSchemaNode::getName) + .containsExactly("root1", "root2", "root3"); + } + + + @Test + void shouldCreateYamlSchemaFromYamlDocument() + throws YamlProcessingException { + // given + YamlDocument documents = YamlLoadingUtils.loadSimpleValidYamlSchemaFile(); + + // when + YamlSchema schema = new YamlSchemaFactory().createTreeStructuredYamlSchema(documents); + + // then + assertThat(schema).isNotNull(); + assertThat(schema.getRootNodes()).hasSize(1); + YamlSchemaNode pmMetaData = schema.getRootNodes().get(0); + assertThatBranchNodeIsValid(pmMetaData, "pmMetaData", "/", true, EMPTY_COMMENT, + 2); + + YamlSchemaNode pmHeader = pmMetaData.getNextNodes().get(1); + assertThatBranchNodeIsValid(pmHeader, "pmHeader", "/pmMetaData/", true, EMPTY_COMMENT, + 1); + + YamlSchemaNode nfType = pmHeader.getNextNodes().get(0); + assertThatLeafNodeIsValid(nfType, "nfType", "/pmMetaData/pmHeader/", true, "nfType comment"); + + YamlSchemaNode pmFields = pmMetaData.getNextNodes().get(0); + assertThatBranchNodeIsValid(pmFields, "pmFields", "/pmMetaData/", true, EMPTY_COMMENT, + 2); + + YamlSchemaNode measChangeType = pmFields.getNextNodes().get(1); + assertThatLeafNodeIsValid(measChangeType, "measChangeType", "/pmMetaData/pmFields/", + true, "measChangeType comment", + "added", "modified", "deleted"); + + YamlSchemaNode measAdditionalFields = pmFields.getNextNodes().get(0); + assertThatBranchNodeIsValid(measAdditionalFields, "measAdditionalFields", "/pmMetaData/pmFields/", + true, "measAdditionalFields comment", + 2); + + YamlSchemaNode vendorField1 = measAdditionalFields.getNextNodes().get(0); + assertThatLeafNodeIsValid(vendorField1, "vendorField1", "/pmMetaData/pmFields/measAdditionalFields/", + true, "vendorField1 comment", + "X", "Y", "Z"); + YamlSchemaNode vendorField2 = measAdditionalFields.getNextNodes().get(1); + assertThatLeafNodeIsValid(vendorField2, "vendorField2", "/pmMetaData/pmFields/measAdditionalFields/", + false, "vendorField2 comment", + "A", "B"); + } + + @Test + void shouldThrowYamlParsingExceptionWhenLoadedSchemaIsInvalid() + throws YamlDocumentParsingException { + // given + YamlDocument documents = YamlLoadingUtils.loadSimpleInvalidYamlSchemaFile(); + + //when then + assertThatThrownBy(() -> new YamlSchemaFactory().createTreeStructuredYamlSchema(documents)) + .isInstanceOf(YamlDocumentParsingException.class) + .hasMessageContaining(String.format( + "Fail to parse given objects: %s as yaml document", + documents.getSubStructure("pmMetaData").getYaml().get("structure")) + ); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/schema/node/YamlSchemaNodeFactoryTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/schema/node/YamlSchemaNodeFactoryTest.java new file mode 100644 index 0000000..646b8a2 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/schema/node/YamlSchemaNodeFactoryTest.java @@ -0,0 +1,147 @@ +/* + * Copyright 2020 Nokia + * + * 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. + * + */ + +package org.onap.validation.yaml.schema.node; + +import org.junit.jupiter.api.Test; +import org.onap.validation.yaml.YamlLoadingUtils; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.model.YamlDocument; +import org.onap.validation.yaml.model.YamlDocumentFactory; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.onap.validation.yaml.schema.node.YamlSchemaNodeFactory.EMPTY_COMMENT; + +public class YamlSchemaNodeFactoryTest { + + private static final String ROOT_PATH = "/"; + + @Test + void shouldThrowExceptionDuringLazyLoadingWhenLoadedSchemaHaveInvalidSubStructure() + throws YamlProcessingException { + // given + String nodeName = "pmMetaData"; + YamlDocument document = YamlLoadingUtils.loadSimpleInvalidYamlSchemaForLazyLoadingFile(); + YamlSchemaNode node = new YamlSchemaNodeFactory() + .createNode(nodeName, ROOT_PATH, document.getSubStructure(nodeName)); + + // when + Throwable ex = catchThrowable(node::getNextNodes); + + // then + assertThat(ex) + .isInstanceOf(YamlSchemaNode.YamlSchemaProcessingException.class) + .hasMessageContaining("Lazy loading failed, due to yaml parsing exception."); + } + + @Test + void shouldCreateLeafNodeIfGivenYamlDocumentHaveNoSubStructure() + throws YamlProcessingException { + // given + String nodeName = "leaf_test"; + String comment = "test leaf node"; + List<String> acceptedValues = List.of("val1", "val2"); + Map<Object, Object> nodeInYamlFormat = Map.of( + YamlSchemaNodeFactory.PRESENCE_KEY, YamlSchemaNodeFactory.PRESENCE_REQUIRED_KEY, + YamlSchemaNodeFactory.COMMENT_KEY, comment, + YamlSchemaNodeFactory.VALUE_KET, acceptedValues); + YamlDocument document = new YamlDocumentFactory().createYamlDocument(nodeInYamlFormat); + + // when + YamlSchemaNode yamlSchemaNode = new YamlSchemaNodeFactory().createNode(nodeName, ROOT_PATH, document); + + // then + assertThatLeafNodeIsValid( + yamlSchemaNode, nodeName, ROOT_PATH, true, comment, + acceptedValues.toArray(new String[0]) + ); + } + + @Test + void shouldCreateBranchNodeIfGivenYamlDocumentHaveSubStructure() + throws YamlProcessingException { + // given + String nodeName = "branch_test"; + String comment = "test branch node"; + + String subNode1Name = "branch_test_node1"; + String subNode2Name = "branch_test_node2"; + + Map<Object, Object> subStructure = Map.of( + subNode1Name, new HashMap<>(), + subNode2Name, new HashMap<>()); + + Map<Object, Object> nodeInYamlFormat = Map.of( + YamlSchemaNodeFactory.PRESENCE_KEY, YamlSchemaNodeFactory.PRESENCE_REQUIRED_KEY, + YamlSchemaNodeFactory.COMMENT_KEY, comment, + YamlSchemaNodeFactory.STRUCTURE_KEY, subStructure); + YamlDocument document = new YamlDocumentFactory().createYamlDocument(nodeInYamlFormat); + + // when + YamlSchemaNode yamlSchemaNode = new YamlSchemaNodeFactory().createNode(nodeName, ROOT_PATH, document); + + // then + assertThatBranchNodeIsValid(yamlSchemaNode, nodeName, ROOT_PATH, true, comment, 2); + List<YamlSchemaNode> subNodes = yamlSchemaNode.getNextNodes(); + assertThat(subNodes).hasSize(2); + assertThatLeafNodeIsValid( + subNodes.get(1), subNode1Name, ROOT_PATH + nodeName + "/", false, EMPTY_COMMENT); + assertThatLeafNodeIsValid( + subNodes.get(0), subNode2Name, ROOT_PATH + nodeName + "/", false, EMPTY_COMMENT); + } + + public static void assertThatBranchNodeIsValid( + YamlSchemaNode yamlSchemaNode, String name, String path, boolean isRequired, String comment, + int numberOfSubNodes + ) throws YamlSchemaNode.YamlSchemaProcessingException { + assertThatNodeIsValid(yamlSchemaNode, name, path, isRequired, comment); + + assertThat(yamlSchemaNode.getClass()).isEqualTo(YamlSchemaBranchNode.class); + assertThat(yamlSchemaNode.isContainingSubStructure()).isTrue(); + assertThat(yamlSchemaNode.getNextNodes()).hasSize(numberOfSubNodes); + assertThat(yamlSchemaNode.getAcceptedValues()).isEmpty(); + } + + public static void assertThatLeafNodeIsValid( + YamlSchemaNode yamlSchemaNode, String name, String path, boolean isRequired, String comment, + String... acceptedValues + ) throws YamlSchemaNode.YamlSchemaProcessingException { + assertThatNodeIsValid(yamlSchemaNode, name, path, isRequired, comment); + + assertThat(yamlSchemaNode.getClass()).isEqualTo(YamlSchemaLeafNode.class); + assertThat(yamlSchemaNode.isContainingSubStructure()).isFalse(); + assertThat(yamlSchemaNode.getAcceptedValues()).containsExactly(acceptedValues); + assertThat(yamlSchemaNode.getNextNodes()).isEmpty(); + } + + private static void assertThatNodeIsValid(YamlSchemaNode yamlSchemaNode, String name, String path, boolean isRequired, String comment) { + assertThat(yamlSchemaNode).isNotNull(); + assertThat(yamlSchemaNode.getName()).isEqualTo(name); + assertThat(yamlSchemaNode.getPath()).isEqualTo(path); + if (comment.isEmpty()) { + assertThat(yamlSchemaNode.getComment()).isNotEmpty(); + } else { + assertThat(yamlSchemaNode.getComment()).isEqualTo(comment); + } + assertThat(yamlSchemaNode.isRequired()).isEqualTo(isRequired); + } +} diff --git a/dictionaryvalidation/src/test/java/org/onap/validation/yaml/util/ArgsTest.java b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/util/ArgsTest.java new file mode 100644 index 0000000..0090683 --- /dev/null +++ b/dictionaryvalidation/src/test/java/org/onap/validation/yaml/util/ArgsTest.java @@ -0,0 +1,39 @@ +/* + *Copyright 2020 Nokia + * + * 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. + * + */ +package org.onap.validation.yaml.util; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.List; + +class ArgsTest { + + @Test + void shouldThrowAnExceptionWhenArgIsNotAvailable() { + Args args = new Args(List.of()); + Assertions.assertThatThrownBy(() -> args.getArg(0)).hasMessage("Argument with index 0 is not available!"); + } + + @Test + void shouldReturnArgumentForGivenIndex() { + Args args = new Args(List.of("one","two", "three")); + Assertions.assertThat(args.getArg(0)).isEqualTo("one"); + Assertions.assertThat(args.getArg(1)).isEqualTo("two"); + Assertions.assertThat(args.getArg(2)).isEqualTo("three"); + } +} |