From bb56d1bcc20d7321f923ab3fae9c6a15c1e92a40 Mon Sep 17 00:00:00 2001 From: Bogumil Zebek Date: Fri, 11 Dec 2020 13:56:54 +0100 Subject: Add cli to pmdictionary validation - Extend pmdictionary validation library by cli Change-Id: Id24bca84f985b2859eff1eeb5bcf0c443269a947 Issue-ID: VNFSDK-715 Signed-off-by: Zebek Bogumil --- pmdictionaryvalidation/pom.xml | 65 ++++++++++ .../main/java/org/onap/validation/cli/Main.java | 48 +++++++ .../command/validate/OutputFilePathGenerator.java | 41 ++++++ .../cli/command/validate/ResponseModel.java | 51 ++++++++ .../cli/command/validate/ResponseStorage.java | 30 +++++ .../cli/command/validate/ToJsonConverter.java | 28 ++++ .../validate/ValidatePmDictionaryYamlCommand.java | 92 +++++++++++++ .../java/org/onap/validation/cli/core/Cli.java | 85 ++++++++++++ .../java/org/onap/validation/cli/core/Command.java | 29 +++++ .../onap/validation/cli/core/CommandException.java | 27 ++++ .../onap/validation/cli/core/CommandResponse.java | 40 ++++++ .../java/org/onap/validation/cli/core/Console.java | 41 ++++++ .../java/org/onap/validation/yaml/util/Args.java | 36 ++++++ .../src/main/resources/log4j2.properties | 72 ++++++----- .../java/org/onap/validation/cli/MainCITest.java | 144 +++++++++++++++++++++ .../validate/OutputFilePathGeneratorTest.java | 43 ++++++ .../cli/command/validate/ToJsonConverterTest.java | 69 ++++++++++ .../command/validate/ValidateYamlCommandTest.java | 96 ++++++++++++++ .../java/org/onap/validation/cli/core/CliTest.java | 101 +++++++++++++++ .../cli/util/ToResponseModelConverter.java | 32 +++++ .../validation/yaml/YamlContentValidatorTest.java | 15 ++- .../org/onap/validation/yaml/YamlLoaderTest.java | 2 +- .../org/onap/validation/yaml/YamlLoadingUtils.java | 8 +- .../org/onap/validation/yaml/util/ArgsTest.java | 39 ++++++ .../src/test/resources/Not_Yaml_File.txt | 1 + 25 files changed, 1192 insertions(+), 43 deletions(-) create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/Main.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/OutputFilePathGenerator.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseModel.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseStorage.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ToJsonConverter.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ValidatePmDictionaryYamlCommand.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Cli.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Command.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandException.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandResponse.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Console.java create mode 100644 pmdictionaryvalidation/src/main/java/org/onap/validation/yaml/util/Args.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/cli/MainCITest.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/OutputFilePathGeneratorTest.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ValidateYamlCommandTest.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/cli/core/CliTest.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/cli/util/ToResponseModelConverter.java create mode 100644 pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/util/ArgsTest.java create mode 100644 pmdictionaryvalidation/src/test/resources/Not_Yaml_File.txt diff --git a/pmdictionaryvalidation/pom.xml b/pmdictionaryvalidation/pom.xml index 6952b40..abab102 100644 --- a/pmdictionaryvalidation/pom.xml +++ b/pmdictionaryvalidation/pom.xml @@ -30,6 +30,10 @@ 1.26 5.7.0 3.18.1 + 3.2.4 + 3.5.0 + 2.23.0 + 2.8.6 @@ -48,6 +52,11 @@ snakeyaml ${snakeyaml.version} + + com.google.code.gson + gson + ${gson.version} + org.junit.jupiter @@ -67,5 +76,61 @@ ${assertj-core.version} test + + org.mockito + mockito-core + ${mockito-core.version} + test + + + org.mockito + mockito-junit-jupiter + ${mockito-junit-jupiter.version} + test + + + ${project.artifactId}-${project.version} + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven-shade-plugin.version} + + + + package + + shade + + + true + standalone + true + + + *:* + + META-INF/DEPENDENCIES + META-INF/LICENSE + META-INF/NOTICE + + + + + + + org.onap.validation.cli.Main + + true + + + + + + + + + diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/Main.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/Main.java new file mode 100644 index 0000000..5ab2e69 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/Main.java @@ -0,0 +1,48 @@ +/* + * 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.onap.validation.cli.command.validate.ResponseStorage; +import org.onap.validation.cli.command.validate.ToJsonConverter; +import org.onap.validation.cli.command.validate.ValidatePmDictionaryYamlCommand; +import org.onap.validation.cli.core.Cli; +import org.onap.validation.cli.core.Console; +import org.onap.validation.yaml.util.Args; + +import java.util.List; + +public class Main { + + public static void main(String[] args) { + final Console console = new Console(); + final ResponseStorage storage = new ResponseStorage(); + + System.exit( + run(args, console, storage) + ); + } + + static int run(String[] args, Console console, ResponseStorage responseStorage) { + + Cli cli = new Cli<>(console, responseStorage); + + return cli.run( + new Args(List.of(args)), + new ValidatePmDictionaryYamlCommand(new ToJsonConverter()) + ); + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/OutputFilePathGenerator.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/OutputFilePathGenerator.java new file mode 100644 index 0000000..2ed7285 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/OutputFilePathGenerator.java @@ -0,0 +1,41 @@ +/* + *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 java.nio.file.Path; + +public class OutputFilePathGenerator { + + public static final int FILE_NAME_ABBREVIATION_INDEX = 0; + public static final String BY_PERIOD_REGEX = "\\."; + public static final String POST_FIX = "-validation-results.json"; + + public Path responsePathFor(Path filePath) { + final Path parent = filePath.getParent(); + final String fileNameAbbreviation = getFileNameAbbreviation(filePath); + return Path.of(parent.toString(), createFileName(fileNameAbbreviation)); + } + + private String createFileName(String fileNameAbbreviation) { + return fileNameAbbreviation + POST_FIX; + } + + private String getFileNameAbbreviation(Path filePath) { + final Path fileName = filePath.getFileName(); + return fileName.toString().split(BY_PERIOD_REGEX)[FILE_NAME_ABBREVIATION_INDEX]; + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseModel.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseModel.java new file mode 100644 index 0000000..033031d --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseModel.java @@ -0,0 +1,51 @@ +/* + *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.onap.validation.yaml.error.YamlDocumentValidationError; + +import java.util.Collections; +import java.util.List; + +public class ResponseModel { + + private final String file; + private final ResponseStatus status; + private final List errors; + + public ResponseModel(String file, ResponseStatus status, List errors) { + this.file = file; + this.status = status; + this.errors = errors; + } + + public String getFile() { + return file; + } + + public List getErrors() { + return Collections.unmodifiableList(errors); + } + + public ResponseStatus getStatus() { + return status; + } + + public enum ResponseStatus { + PASS, FAILED + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseStorage.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseStorage.java new file mode 100644 index 0000000..3daed16 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ResponseStorage.java @@ -0,0 +1,30 @@ +/* + *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 java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; + +public class ResponseStorage{ + + public void store(Path filePath, T response) throws IOException { + try (PrintWriter out = new PrintWriter(filePath.toFile())) { + out.println(response); + } + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ToJsonConverter.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ToJsonConverter.java new file mode 100644 index 0000000..168daf8 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ToJsonConverter.java @@ -0,0 +1,28 @@ +/* + *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 com.google.gson.Gson; +import com.google.gson.GsonBuilder; + + +public class ToJsonConverter { + public String convert(ResponseModel responseModel) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + return gson.toJson(responseModel); + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ValidatePmDictionaryYamlCommand.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ValidatePmDictionaryYamlCommand.java new file mode 100644 index 0000000..ceb46d3 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/command/validate/ValidatePmDictionaryYamlCommand.java @@ -0,0 +1,92 @@ +/* + *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.onap.validation.cli.core.Command; +import org.onap.validation.cli.core.CommandException; +import org.onap.validation.cli.core.CommandResponse; +import org.onap.validation.yaml.YamlContentValidator; +import org.onap.validation.yaml.error.YamlDocumentValidationError; +import org.onap.validation.yaml.exception.YamlProcessingException; +import org.onap.validation.yaml.util.Args; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +public class ValidatePmDictionaryYamlCommand implements Command { + + public static final int PATH_TO_FILE_INDEX = 0; + private final YamlContentValidator yamlContentValidator = new YamlContentValidator(); + + private final ToJsonConverter toJsonConverter; + private final OutputFilePathGenerator filePathGenerator = new OutputFilePathGenerator(); + + public ValidatePmDictionaryYamlCommand(ToJsonConverter toJsonConverter) { + this.toJsonConverter = toJsonConverter; + } + + @Override + public CommandResponse execute(Args args) throws CommandException { + final String pathToFile = resolvePathToFile(args); + + try { + return validate(pathToFile); + } catch (YamlProcessingException e) { + throw new CommandException("Provided yaml file has invalid structure!", e); + } + } + + @Override + public String getName() { + return "Validate PM Dictionary yaml"; + } + + @Override + public Path getOutputFilePath(Args args) throws CommandException { + final String pathToFile = resolvePathToFile(args); + return this.filePathGenerator.responsePathFor(Path.of(pathToFile)); + } + + private CommandResponse validate(String pathToFile) throws YamlProcessingException { + final List errors = yamlContentValidator.validate(pathToFile); + return new CommandResponse<>( + toJsonConverter.convert(new ResponseModel(pathToFile, resolveResponseStatus(errors), errors)) + ,resolveCommandStatus(errors) + ); + } + + private ResponseModel.ResponseStatus resolveResponseStatus(List errors) { + return errors.isEmpty() ? ResponseModel.ResponseStatus.PASS : ResponseModel.ResponseStatus.FAILED; + } + + private CommandResponse.CommandStatus resolveCommandStatus(List errors) { + return errors.isEmpty() ? CommandResponse.CommandStatus.PASS : CommandResponse.CommandStatus.FAILED; + } + + private String resolvePathToFile(Args args) throws CommandException { + try { + final String pathToFile = args.getArg(PATH_TO_FILE_INDEX); + if (!Files.exists(Path.of(pathToFile))) { + throw new CommandException(String.format("File '%s' does not exist!", pathToFile)); + } + return pathToFile; + } catch (IllegalArgumentException ex) { + throw new CommandException("Command argument is missing: provide a path to file", ex); + } + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Cli.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Cli.java new file mode 100644 index 0000000..bf2abad --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Cli.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.cli.core; + +import org.onap.validation.cli.command.validate.ResponseStorage; +import org.onap.validation.cli.core.CommandResponse.CommandStatus; +import org.onap.validation.yaml.util.Args; + +import java.nio.file.Path; + +public class Cli { + + public static final int INTERNAL_ERROR_STATUS_CODE = 2; + public static final int FAILED_STATUS_CODE = 1; + public static final int PASS_STATUS_CODE = 0; + + public static final String APPLICATION_INTERNAL_ERROR_MSG = "\n# Application fails with internal error."; + public static final String APPLICATION_EXIT_SUCCESSFULLY_MSG = "\n# Application exits successfully."; + + private final Console console; + private final ResponseStorage responseStorage; + + public Cli(Console console, ResponseStorage responseStorage) { + this.console = console; + this.responseStorage = responseStorage; + } + + public int run(Args args, Command command) { + try { + final CommandResponse commandResponse = processCommand(args, command); + + logResultInfo(commandResponse.getResult()); + storeResult(args, command, commandResponse.getResult()); + + this.console.info(APPLICATION_EXIT_SUCCESSFULLY_MSG); + + return resolveCliStatusCodeFor(commandResponse); + } catch (Exception e) { + logException(e); + return INTERNAL_ERROR_STATUS_CODE; + } + } + + private int resolveCliStatusCodeFor(CommandResponse commandResponse) { + return commandResponse.getCommandStatus() == CommandStatus.PASS ? PASS_STATUS_CODE : FAILED_STATUS_CODE; + } + + private void logException(Exception e) { + this.console.error("# Command error: "); + this.console.error(e); + this.console.error(APPLICATION_INTERNAL_ERROR_MSG); + } + + private void storeResult(Args args, Command command, T result) throws CommandException, java.io.IOException { + final Path pathToFileWithResponse = command.getOutputFilePath(args); + this.responseStorage.store(pathToFileWithResponse, result); + this.console.info(String.format("%n# Result was stored in a file: '%s'", pathToFileWithResponse)); + } + + private void logResultInfo(T result) { + this.console.info("\n# Operation result:\n"); + this.console.info(result.toString()); + } + + private CommandResponse processCommand(Args args, Command command) throws CommandException { + this.console.info(String.format("# Executing a '%s' operation ...", command.getName())); + final CommandResponse commandResponse = command.execute(args); + this.console.info("# ... Done."); + return commandResponse; + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Command.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Command.java new file mode 100644 index 0000000..1da724f --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Command.java @@ -0,0 +1,29 @@ +/* + *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.onap.validation.yaml.util.Args; + +import java.nio.file.Path; + +public interface Command { + CommandResponse execute(Args args) throws CommandException; + + String getName(); + + Path getOutputFilePath(Args args) throws CommandException; +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandException.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandException.java new file mode 100644 index 0000000..2c72ff8 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandException.java @@ -0,0 +1,27 @@ +/* + *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; + +public class CommandException extends Exception { + public CommandException(String msg) { + super(msg); + } + + public CommandException(String msg, Exception ex) { + super(msg, ex); + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandResponse.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandResponse.java new file mode 100644 index 0000000..e9f70ca --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/CommandResponse.java @@ -0,0 +1,40 @@ +/* + *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; + +public class CommandResponse { + + private final T result; + private final CommandStatus commandStatus; + + public CommandResponse(T result, CommandStatus commandStatus) { + this.result = result; + this.commandStatus = commandStatus; + } + + public T getResult() { + return result; + } + + public CommandStatus getCommandStatus() { + return commandStatus; + } + + public enum CommandStatus { + PASS, FAILED + } +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Console.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Console.java new file mode 100644 index 0000000..4c20437 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/cli/core/Console.java @@ -0,0 +1,41 @@ +/* + *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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Console { + + public static final Logger logger = LoggerFactory.getLogger(Console.class); + + public void info(String msg) { + System.out.println(msg); + logger.info(msg); + } + + public void error(Exception ex) { + System.err.println(ex.getMessage() + ", more information in log file."); + logger.error("Internal error", ex); + } + + public void error(String msg) { + System.err.println(msg); + logger.error(msg); + } + +} diff --git a/pmdictionaryvalidation/src/main/java/org/onap/validation/yaml/util/Args.java b/pmdictionaryvalidation/src/main/java/org/onap/validation/yaml/util/Args.java new file mode 100644 index 0000000..9ae44c8 --- /dev/null +++ b/pmdictionaryvalidation/src/main/java/org/onap/validation/yaml/util/Args.java @@ -0,0 +1,36 @@ +/* + *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 java.util.ArrayList; +import java.util.List; + +public class Args { + + private final List data; + + public Args(List data) { + this.data = new ArrayList<>(data); + } + + public String getArg(int index) { + if (this.data.size() <= index) { + throw new IllegalArgumentException(String.format("Argument with index %d is not available!", index)); + } + return this.data.get(index); + } +} diff --git a/pmdictionaryvalidation/src/main/resources/log4j2.properties b/pmdictionaryvalidation/src/main/resources/log4j2.properties index f3202ee..c7e5092 100644 --- a/pmdictionaryvalidation/src/main/resources/log4j2.properties +++ b/pmdictionaryvalidation/src/main/resources/log4j2.properties @@ -1,4 +1,4 @@ -# Copyright Nokia 2020,2020 Huawei Technologies Co., Ltd. +# Copyright Nokia 2020 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,34 +15,42 @@ # By default, log4j2 will look for a configuration file named log4j2.xml on the classpath. # reference: https://logging.apache.org/log4j/2.x/faq.html#troubleshooting -rootLogger.level=ERROR -rootLogger.appenderRefs=file -rootLogger.appenderRef.file.ref=RollingFile - -logger.onap.name = org.onap -logger.onap.level=ERROR -logger.onap.additivity=false -logger.onap.appenderRef.stdout.ref=STDOUT - -appenders=stdout, file - -# Direct log messages to stdout -appender.stdout.type=Console -appender.stdout.name=STDOUT -appender.stdout.target=SYSTEM_OUT -appender.stdout.layout.type=PatternLayout -appender.stdout.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file, support file rolling. -appender.file.type = RollingFile -appender.file.name = RollingFile -appender.file.fileName=./pmdictionary-validate.log -appender.file.filePattern=./pmdictionary-validate.%d{yyyy-MM-dd-HH:mm:ss}.log -appender.file.append=true -appender.file.policies.type=Policies -appender.file.policies.size.type=SizeBasedTriggeringPolicy -appender.file.policies.size.size=5MB -appender.file.strategy.type=DefaultRolloverStrategy -appender.file.strategy.max=10 -appender.file.layout.type=PatternLayout -appender.file.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n + +status = error +dest = err +name = PropertiesConfig + +property.filename = ./pmdictionary-validate.log + +filter.threshold.type = ThresholdFilter +filter.threshold.level = debug + +appender.console.type = Console +appender.console.name = STDOUT +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %m%n +appender.console.filter.threshold.type = ThresholdFilter +appender.console.filter.threshold.level = error + +appender.rolling.type = RollingFile +appender.rolling.name = RollingFile +appender.rolling.fileName = ${filename} +appender.rolling.filePattern = ./pmdictionary-validate.%d{yyyy-MM-dd-HH:mm:ss}.log +appender.rolling.layout.type = PatternLayout +appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n +appender.rolling.policies.type = Policies +appender.rolling.policies.time.type = TimeBasedTriggeringPolicy +appender.rolling.policies.time.interval = 2 +appender.rolling.policies.time.modulate = true +appender.rolling.policies.size.type = SizeBasedTriggeringPolicy +appender.rolling.policies.size.size=5MB +appender.rolling.strategy.type = DefaultRolloverStrategy +appender.rolling.strategy.max = 5 + +logger.rolling.name = org.onap.validation +logger.rolling.level = debug +logger.rolling.additivity = false +logger.rolling.appenderRef.rolling.ref = RollingFile + +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = STDOUT diff --git a/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/MainCITest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/MainCITest.java new file mode 100644 index 0000000..c6eb2ad --- /dev/null +++ b/pmdictionaryvalidation/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.util.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 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 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 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 consoleInfoCaptor = ArgumentCaptor.forClass(String.class); + verify(console, times(6)).info(consoleInfoCaptor.capture()); + final List 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/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/OutputFilePathGeneratorTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/OutputFilePathGeneratorTest.java new file mode 100644 index 0000000..b4d68b4 --- /dev/null +++ b/pmdictionaryvalidation/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/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java new file mode 100644 index 0000000..3c97681 --- /dev/null +++ b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ToJsonConverterTest.java @@ -0,0 +1,69 @@ +/* + *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.util.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/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ValidateYamlCommandTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/command/validate/ValidateYamlCommandTest.java new file mode 100644 index 0000000..6347f75 --- /dev/null +++ b/pmdictionaryvalidation/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.util.ToResponseModelConverter.toModel; + +@ExtendWith(MockitoExtension.class) +class ValidateYamlCommandTest { + + private final ToJsonConverter toJsonConverter = new ToJsonConverter(); + private ValidatePmDictionaryYamlCommand validateYamlCommand; + + @BeforeEach + void setUp() { + this.validateYamlCommand = new ValidatePmDictionaryYamlCommand(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 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 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/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/core/CliTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/core/CliTest.java new file mode 100644 index 0000000..c8ad629 --- /dev/null +++ b/pmdictionaryvalidation/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 validationCommand; + + private Cli 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/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/util/ToResponseModelConverter.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/util/ToResponseModelConverter.java new file mode 100644 index 0000000..d78f493 --- /dev/null +++ b/pmdictionaryvalidation/src/test/java/org/onap/validation/cli/util/ToResponseModelConverter.java @@ -0,0 +1,32 @@ +/* + *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.util; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.onap.validation.cli.command.validate.ResponseModel; + +public final class ToResponseModelConverter { + + private ToResponseModelConverter() { + } + + public static ResponseModel toModel(String json) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + return gson.fromJson(json, ResponseModel.class); + } +} diff --git a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java index b6c2548..1412085 100644 --- a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java +++ b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlContentValidatorTest.java @@ -29,16 +29,19 @@ 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_VALID_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_VALID_YAML); + String path = getFullPathForGivenResources(PATH_TO_YAML_WITH_WRONG_VALUES); // when List validationErrors = new YamlContentValidator().validate(path); @@ -65,7 +68,7 @@ class YamlContentValidatorTest { String path = getFullPathForGivenResources(PATH_TO_MULTI_DOCUMENT_INVALID_YAML); //when then - assertThatThrownBy(() -> new YamlContentValidator().validate(path)) + assertThatThrownBy(() -> yamlContentValidator.validate(path)) .isInstanceOf(ParserException.class) .hasMessageContaining("expected the node content, but found ''"); } @@ -76,7 +79,7 @@ class YamlContentValidatorTest { String path = "invalid/path/to/pm_dictionary"; //when then - assertThatThrownBy(() -> new YamlContentValidator().validate(path)) + assertThatThrownBy(() -> yamlContentValidator.validate(path)) .isInstanceOf(YamlProcessingException.class) .hasMessageContaining("PM_Dictionary YAML file is empty"); } @@ -87,7 +90,7 @@ class YamlContentValidatorTest { @Test void shouldReturnCorrectErrorsWhenGivenPmDictionaryFileWithErrors() throws YamlProcessingException, IOException { // given - byte[] yaml = readFile(PATH_TO_VALID_YAML); + byte[] yaml = readFile(PATH_TO_YAML_WITH_WRONG_VALUES); // when List validationErrors = new YamlContentValidator().validate(yaml); @@ -158,4 +161,4 @@ class YamlContentValidatorTest { private String getFullPathForGivenResources(String pathToValidYaml) { return this.getClass().getClassLoader().getResource(pathToValidYaml).getPath(); } -} \ No newline at end of file +} diff --git a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java index 3b26541..3e1f601 100644 --- a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java +++ b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoaderTest.java @@ -106,7 +106,7 @@ class YamlLoaderTest { @Test void shouldLoadAllDocumentsFromYamlFile() throws YamlDocumentFactory.YamlDocumentParsingException, IOException { // when - List documents = YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_VALID_YAML)); + List documents = YAML_LOADER.loadMultiDocumentYaml(YamlLoadingUtils.readFile(YamlLoadingUtils.PATH_TO_YAML_WITH_WRONG_VALUES)); // then assertThat(documents).hasSize(EXPECTED_NUMBER_OF_DOCUMENTS); diff --git a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java index b16d3ea..dc1ce3b 100644 --- a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java +++ b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/YamlLoadingUtils.java @@ -39,7 +39,7 @@ public final class YamlLoadingUtils { 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_VALID_YAML = "yaml_schema/PM_Dictionary.yaml"; + 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"; @@ -50,7 +50,7 @@ public final class YamlLoadingUtils { public static final String PATH_TO_INVALID_YAML_WITH_UNKNOWN_ESCAPE_CHARACTER = "yaml_schema/Simple_Unknown_Escape_Character.yaml"; public static List loadValidMultiDocumentYamlFile() throws YamlDocumentParsingException { - return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_VALID_YAML)); + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_YAML_WITH_WRONG_VALUES)); } public static List loadValidJsonStyleMultiDocumentYamlFile() throws YamlDocumentParsingException { @@ -58,7 +58,7 @@ public final class YamlLoadingUtils { } public static List loadValidMultiDocumentYamlFileUsingStringPath() throws YamlProcessingException { - return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_VALID_YAML).getPath()); + return YAML_LOADER.loadMultiDocumentYamlFile(getUrlForGivenPath(PATH_TO_YAML_WITH_WRONG_VALUES).getPath()); } public static YamlDocument loadSimpleValidYamlSchemaFile() throws YamlDocumentParsingException { @@ -98,7 +98,7 @@ public final class YamlLoadingUtils { return Files.readAllBytes(Path.of(file)); } - private static URL getUrlForGivenPath(String path) { + public static URL getUrlForGivenPath(String path) { return YamlLoadingUtils.class.getClassLoader().getResource(path); } } diff --git a/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/util/ArgsTest.java b/pmdictionaryvalidation/src/test/java/org/onap/validation/yaml/util/ArgsTest.java new file mode 100644 index 0000000..0090683 --- /dev/null +++ b/pmdictionaryvalidation/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"); + } +} diff --git a/pmdictionaryvalidation/src/test/resources/Not_Yaml_File.txt b/pmdictionaryvalidation/src/test/resources/Not_Yaml_File.txt new file mode 100644 index 0000000..be6ee44 --- /dev/null +++ b/pmdictionaryvalidation/src/test/resources/Not_Yaml_File.txt @@ -0,0 +1 @@ +Not a Yaml file! -- cgit 1.2.3-korg