#other properties to load (it should be hanled when plugins are made as externally register-able
#when command plugin management support is enabled in oclip
-cli.schema.profile.confs=open-cli-http.properties,open-cli-snmp.properties
-
+cli.schema.profile.confs=open-cli-http.properties,open-cli-snmp.properties
\ No newline at end of file
package org.onap.cli.fw.cmd;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
import org.onap.cli.fw.conf.OnapCommandConstants;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.output.OnapCommandResultAttribute;
import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
import org.onap.cli.fw.output.OnapCommandResultType;
+import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
import org.onap.cli.fw.schema.OnapCommandSchemaLoader;
import org.onap.cli.fw.schema.OnapCommandSchemaMerger;
+import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
import org.onap.cli.fw.utils.OnapCommandHelperUtils;
import org.onap.cli.fw.utils.OnapCommandUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
/**
* Oclip Command.
return this.initializeSchema(schema, false);
}
-
public List<String> initializeSchema(String schema, boolean validate) throws OnapCommandException {
this.setSchemaName(schema);
}
}
+ protected void preRun() throws OnapCommandException {
+ LOG.debug("CMD: " + this.getName() + "pre run.");
+ }
+
+ protected void postRun() throws OnapCommandException {
+ LOG.debug("CMD: " + this.getName() + "post run.");
+ }
/**
* Oclip command execute with given parameters on service. Before calling this method, its mandatory to set all
* parameters value.
}
}
+ preRun();
+
this.run();
LOG.info("OUTPUT: " + this.cmdResult.getRecords());
+ postRun();
return this.cmdResult;
}
public String printHelp() throws OnapCommandHelpFailed {
return OnapCommandHelperUtils.help(this);
}
-
// (mrkanag) Add toString for all command, parameter, result, etc objects in JSON format
}
public static final String SAMPLE_GEN_ENABLED = "cli.sample.gen.enable";
public static final String SAMPLE_GEN_TARGET_FOLDER = "cli.sample.gen.target";
+ public static final String VERIFY_SAMPLES_DIRECTORY = "open-cli-sample";
+ public static final String VERIFY_SAMPLES_FILE_PATTERN = VERIFY_SAMPLES_DIRECTORY + YAML_PATTERN;
+ public static final String VERIFY_SAMPLES_MOCK_PATTERN = VERIFY_SAMPLES_DIRECTORY + JSON_PATTERN;
+ public static final String VERIFY_SAMPLES = "samples";
+ public static final String VERIFY_CMD_NAME = "name";
+ public static final String VERIFY_CMD_VERSION = "version";
+ public static final String VERIFY_OUPUT = "output";
+ public static final String VERIFY_INPUT = "input";
+ public static final String VERIFY_MOCO = "moco";
+ public static final String VERIFY_SAMPLE_FILE_ID = "samplefileid";
+ public static final String VERIFY_SAMPLE_ID = "sampleid";
+ public static final String VERIFY_RESULT_PASS = "pass";
+ public static final String VERIFY_RESULT_FAIL = "fail";
+ public static final String VERIFY_CONTEXT_PARAM = "context";
+
+
+
+ public static final String VERIFY_LONG_OPTION = "--verify";
+ public static final String VERIFY_SHORT_OPTION = "-V";
+
private OnapCommandConstants() {
}
package org.onap.cli.fw.registrar;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
import org.apache.commons.io.IOUtils;
import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.conf.OnapCommandConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
/**
* Oclip Command registrar provides a common place, where every command would get registered automatically when its
public void setProfile(String profileName, List<String> includes, List<String> excludes) {
this.paramCache.setProfile(profileName);
- for (String profile: includes) {
+ for (String profile : includes) {
this.paramCache.includeProfile(profile);
}
- for (String profile: excludes) {
+ for (String profile : excludes) {
this.paramCache.excludeProfile(profile);
}
}
/**
* Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command.
*
- * @param name
- * Command Name
- * @param cmd
- * Command Class
- * @throws OnapCommandInvalidRegistration
- * Invalid registration exception
+ * @param name Command Name
+ * @param cmd Command Class
+ * @throws OnapCommandInvalidRegistration Invalid registration exception
* @throws OnapCommandRegistrationProductInfoMissing
*/
private void register(String name, String version, Class<? extends OnapCommand> cmd) throws OnapCommandInvalidRegistration, OnapCommandRegistrationProductInfoMissing {
private OnapCommandRegistrar() {
this.enabledProductVersion = System.getenv(OnapCommandConstants.OPEN_CLI_PRODUCT_IN_USE_ENV_NAME);
- if (this.enabledProductVersion == null) {
- this.enabledProductVersion = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME);
+ if (this.enabledProductVersion == null) {
+ this.enabledProductVersion = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME);
}
}
/**
* Get global registrar.
*
- * @throws OnapCommandException
- * exception
+ * @throws OnapCommandException exception
*/
public static OnapCommandRegistrar getRegistrar() throws OnapCommandException {
if (registrar == null) {
return cmds;
}
- for (String cmd: this.registry.keySet()) {
+ for (String cmd : this.registry.keySet()) {
if (cmd.split(":")[1].equalsIgnoreCase(version)) {
cmds.add(cmd.split(":")[0]);
}
* Returns command details.
*
* @return map
- * @throws OnapCommandException
- * exception
+ * @throws OnapCommandException exception
*/
public List<OnapCommandSchemaInfo> listCommandInfo() throws OnapCommandException {
return OnapCommandDiscoveryUtils.discoverSchemas();
/**
* Get the OnapCommand, which CLI main would use to find the command based on the command name.
*
- * @param cmdName
- * Name of command
+ * @param cmdName Name of command
* @return OnapCommand
- * @throws OnapCommandException
- * Exception
+ * @throws OnapCommandException Exception
*/
public OnapCommand get(String cmdName) throws OnapCommandException {
return this.get(cmdName, this.getEnabledProductVersion());
/**
* Get the OnapCommand, which CLI main would use to find the command based on the command name.
*
- * @param cmdName
- * Name of command
- * @param version
- * product version
+ * @param cmdName Name of command
+ * @param version product version
* @return OnapCommand
- * @throws OnapCommandException
- * Exception
+ * @throws OnapCommandException Exception
*/
public OnapCommand get(String cmdName, String version) throws OnapCommandException {
Class<? extends OnapCommand> cls = registry.get(cmdName + ":" + version);
}
//First check if there is an specific plugin exist, otherwise check for profile plugin
- if (plugins.containsKey(schema.getSchemaName())) {
- this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName()));
- } else if (plugins.containsKey(schema.getSchemaProfile())) {
+ if (plugins.containsKey(schema.getSchemaName())) {
+ this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName()));
+ } else if (plugins.containsKey(schema.getSchemaProfile())) {
this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaProfile()));
} else {
LOG.info("Ignoring schema " + schema.getSchemaURI());
}
String buildTime = OnapCommandHelperUtils.findLastBuildTime();
- if (buildTime!= null && !buildTime.isEmpty()) {
+ if (buildTime != null && !buildTime.isEmpty()) {
buildTime = " [" + buildTime + "]";
} else {
buildTime = "";
* Provides the help message in tabular format for all commands registered in this registrar.
*
* @return string
- * @throws OnapCommandHelpFailed
- * Help cmd failed
+ * @throws OnapCommandHelpFailed Help cmd failed
*/
public String getHelp() throws OnapCommandHelpFailed {
return this.getHelp(false);
OnapCommand cmd;
try {
if (!isEnabledProductVersionOnly) {
- String []cmdVer = cmdName.split(":");
+ String[] cmdVer = cmdName.split(":");
cmd = this.get(cmdVer[0], cmdVer[1]);
attr.getValues().add(cmdVer[0]);
attrVer.getValues().add(cmdVer[1]);
throw new OnapCommandHelpFailed(e);
}
}
+
+ public List<Map<String, ?>> getTestSuite(String cmd) throws OnapCommandException {
+ return OnapCommandDiscoveryUtils.createTestSuite(cmd, enabledProductVersion);
+ }
}
import org.onap.cli.fw.cmd.OnapCommandType;
import org.onap.cli.fw.conf.OnapCommandConstants;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* OnapCommandSchemaInfo is used in discovery caching.
*
private String product;
+ private List<String> sampleFiles = new ArrayList();
+
/**
* OCS version
*/
this.ignore = ignore;
}
-
+ public List<String> getSampleFiles() {
+ return sampleFiles;
+ }
}
import java.util.Map;
import java.util.Set;
+import org.apache.commons.io.FileUtils;
import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.cmd.OnapCommandType;
import org.onap.cli.fw.conf.OnapCommandConfig;
/**
* Get schema map.
*
- * @param resource
- * resource obj
- * @return map
- * @throws OnapCommandInvalidSchema
- * exception
- */
- public static Map<String, ?> loadSchema(Resource resource) throws OnapCommandInvalidSchema {
- try {
- return loadSchema(resource.getInputStream(), resource.getFilename());
- } catch (IOException e) {
- throw new OnapCommandInvalidSchema(resource.getFilename(), e);
- }
-
- }
-
- /**
- * Get schema map.
- *
- * @param resource
- * resource obj
+ * @param stream
+ * @param schemaName
* @return map
* @throws OnapCommandInvalidSchema
* exception
package org.onap.cli.fw.utils;
-import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_DIRECTORY;
-import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_JSON_PATTERN;
-import static org.onap.cli.fw.conf.OnapCommandConstants.DISCOVERY_FILE;
-import static org.onap.cli.fw.conf.OnapCommandConstants.NAME;
-import static org.onap.cli.fw.conf.OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION;
-import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_DIRECTORY;
-import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_PATH_PATERN;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.Map.Entry;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.io.FileUtils;
import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.conf.OnapCommandConfig;
import org.onap.cli.fw.conf.OnapCommandConstants;
-import org.onap.cli.fw.error.OnapCommandDiscoveryFailed;
-import org.onap.cli.fw.error.OnapCommandException;
-import org.onap.cli.fw.error.OnapCommandInstantiationFailed;
-import org.onap.cli.fw.error.OnapCommandInvalidSchema;
+import org.onap.cli.fw.error.*;
+import org.onap.cli.fw.registrar.OnapCommandRegistrar;
import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
import org.onap.cli.fw.schema.OnapCommandSchemaLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.yaml.snakeyaml.Yaml;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.*;
+
+import static org.onap.cli.fw.conf.OnapCommandConstants.*;
public class OnapCommandDiscoveryUtils {
for (Resource resource : res) {
try {
- resourceMap = OnapCommandSchemaLoader.loadSchema(resource);
+ resourceMap = loadYaml(resource);
} catch (OnapCommandException e) {
OnapCommandUtils.LOG.error("Ignores invalid schema " + resource.getURI().toString(), e);
continue;
throw new OnapCommandDiscoveryFailed(SCHEMA_DIRECTORY, e);
}
+ try {
+ Resource[] samples = findResources(OnapCommandConstants.VERIFY_SAMPLES_FILE_PATTERN);
+ for (Resource sample : samples) {
+ updateSchemaInfoWithSample(sample, extSchemas);
+ }
+ } catch (IOException e) {
+ throw new OnapCommandDiscoveryFailed(OnapCommandConstants.VERIFY_SAMPLES_DIRECTORY, e);
+ }
+
return extSchemas;
}
+ private static void updateSchemaInfoWithSample(Resource sampleResourse,
+ List<OnapCommandSchemaInfo> schemaInfos) throws OnapCommandInvalidSchema, IOException {
+ Map<String, ?> infoMap = loadSchema(sampleResourse);
+ String cmdName = (String) infoMap.get(OnapCommandConstants.VERIFY_CMD_NAME);
+ String version = (String) infoMap.get(OnapCommandConstants.VERIFY_CMD_VERSION);
+
+ Optional<OnapCommandSchemaInfo> optSchemaInfo = schemaInfos.stream()
+ .filter(e -> e.getCmdName().equals(cmdName) && e.getProduct().equals(version))
+ .findFirst();
+
+ if (optSchemaInfo.isPresent()) {
+ OnapCommandSchemaInfo onapCommandSchemaInfo = optSchemaInfo.get();
+ onapCommandSchemaInfo.getSampleFiles().add(sampleResourse.getFilename());
+ }
+ }
+
/**
* Discover the Oclip commands.
*
}
}
+
+ public static List<Map<String, ?>> createTestSuite(String cmd, String version) throws OnapCommandException {
+
+ ArrayList<Map<String, ?>> testSamples = new ArrayList();
+
+ List<Resource> resources = new ArrayList();
+ OnapCommandSchemaInfo schemaInfo = getSchemaInfo(cmd, version);
+
+ List<String> sampleFiles = new ArrayList();
+ if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) {
+ sampleFiles.addAll(schemaInfo.getSampleFiles());
+ }
+
+ for (String sampleFile : sampleFiles) {
+ try {
+ Resource resource = OnapCommandDiscoveryUtils.findResource(sampleFile,
+ OnapCommandConstants.VERIFY_SAMPLES_FILE_PATTERN);
+ resources.add(resource);
+ } catch (IOException e) {
+ throw new OnapCommandInvalidSample("Sample file does not exist : " + sampleFile , e);
+ }
+ }
+
+ for (Resource resource : resources) {
+
+ Map<String, ?> stringMap = OnapCommandDiscoveryUtils.loadYaml(resource);
+ Map<String, Map<String, String>> samples = (Map<String, Map<String, String>>) stringMap
+ .get(OnapCommandConstants.VERIFY_SAMPLES);
+
+ for (String sampleId : samples.keySet()) {
+
+ Map<String, String> sample = samples.get(sampleId);
+
+ List<String> inputArgs = new ArrayList();
+ inputArgs.add(cmd);
+ if (sample.get(OnapCommandConstants.VERIFY_INPUT) != null) {
+ inputArgs.addAll(Arrays.asList(sample.get(OnapCommandConstants.VERIFY_INPUT).trim().split(" ")));
+ }
+ inputArgs.add(OnapCommandConstants.VERIFY_LONG_OPTION);
+
+ HashMap map = new HashMap();
+ map.put(OnapCommandConstants.VERIFY_INPUT, inputArgs);
+ map.put(OnapCommandConstants.VERIFY_OUPUT, sample.get(OnapCommandConstants.VERIFY_OUPUT));
+ map.put(OnapCommandConstants.VERIFY_MOCO, sample.get(OnapCommandConstants.VERIFY_MOCO));
+ map.put(OnapCommandConstants.VERIFY_SAMPLE_FILE_ID, resource.getFilename());
+ map.put(OnapCommandConstants.VERIFY_SAMPLE_ID, sampleId);
+ testSamples.add(map);
+ }
+ }
+ return testSamples;
+ }
+
+ /**
+ * Get schema map.
+ *
+ * @param resource
+ * resource obj
+ * @return map
+ * @throws OnapCommandInvalidSchema
+ * exception
+ */
+ public static Map<String, ?> loadYaml(Resource resource) throws OnapCommandInvalidSchema {
+ Map<String, ?> values = null;
+ try {
+ values = (Map<String, ?>) new Yaml().load(resource.getInputStream());
+ } catch (Exception e) {
+ throw new OnapCommandInvalidSchema(resource.getFilename(), e);
+ }
+ return values;
+ }
+
+ /**
+ * Get schema map.
+ *
+ * @param filePath
+ * @return map
+ * @throws OnapCommandInvalidSchema
+ * exception
+ */
+ public static Map<String, ?> loadYaml(String filePath) throws OnapCommandInvalidSchema {
+ Map<String, ?> values = null;
+ try {
+ values = (Map<String, Object>) new Yaml().load(FileUtils.readFileToString(new File(filePath)));
+ } catch (Exception e) {
+ throw new OnapCommandInvalidSchema(filePath, e);
+ }
+ return values;
+ }
}
long_option: no-title
default_value: false
is_default_param: true
+ - name: verify
+ type: bool
+ description: verify the command using available command sample file and mocking file
+ short_option: V
+ long_option: verify
+ default_value: false
+ is_default_param: true
+ is_include: false
+ is_optional: true
- name: context
type: map
description: command context
short_option: D
long_option: context
is_default_param: true
+ is_optional: true
is_optional: true
\ No newline at end of file
}
Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters());
- assertTrue(map.size() == 17);
+ assertTrue(map.size() == 18);
}
@Test
<artifactId>cli-framework</artifactId>
<version>${project.parent.version}</version>
</dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>1.3.2</version>
- </dependency>
<dependency>
<groupId>jline</groupId>
<artifactId>jline</artifactId>
package org.onap.cli.main;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.commons.io.FileUtils;
+import jline.TerminalFactory;
+import jline.console.ConsoleReader;
import org.apache.commons.io.IOUtils;
import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.conf.OnapCommandConfig;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.error.OnapCommandHelpFailed;
import org.onap.cli.fw.error.OnapCommandInvalidSample;
-import org.onap.cli.fw.error.OnapCommandInvalidSchema;
import org.onap.cli.fw.error.OnapCommandWarning;
import org.onap.cli.fw.input.OnapCommandParameter;
import org.onap.cli.fw.output.OnapCommandPrintDirection;
import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
import org.onap.cli.fw.output.OnapCommandResultType;
import org.onap.cli.fw.registrar.OnapCommandRegistrar;
+import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
import org.onap.cli.main.conf.OnapCliConstants;
import org.onap.cli.main.interactive.StringCompleter;
import org.onap.cli.main.utils.OnapCliArgsParser;
import org.onap.cli.sample.yaml.SampleYamlGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.yaml.snakeyaml.Yaml;
-import jline.TerminalFactory;
-import jline.console.ConsoleReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
/**
* Oclip Command Line Interface (CLI).
public void handleHelp() {
try {
if ((args.size() == 1) && (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(0))
- || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(0)))) {
+ || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(0)))) {
this.print(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("oclip-readme.txt")));
String help = OnapCommandRegistrar.getRegistrar().getHelp();
this.print(help);
public void handleProfile() {
try {
if ((this.args.size() >= 2) && (this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG).equals(this.args.get(0))
- || this.getShortOption(OnapCliConstants.PARAM_PROFILE_SHORT).equals(this.args.get(0)))) {
+ || this.getShortOption(OnapCliConstants.PARAM_PROFILE_SHORT).equals(this.args.get(0)))) {
OnapCommandRegistrar.getRegistrar().setProfile(
this.args.get(1),
public void handleBatchCommand() {
try {
if ((this.args.size() >= 3) && (this.getLongOption(OnapCliConstants.PARAM_PARAM_FILE_LONG).equals(this.args.get(0))
- || this.getShortOption(OnapCliConstants.PARAM_PARAM_FILE_SHORT).equals(this.args.get(0)))) {
+ || this.getShortOption(OnapCliConstants.PARAM_PARAM_FILE_SHORT).equals(this.args.get(0)))) {
String paramFilePath = this.args.get(1);
//Read YAML and loop thru it
// one
- // - param-long-option-1: value
- // - param-long-option-1: value
- // - positional-arg1
- // - positional-arg2
- // two
- // - param-long-option-1: value
- // - param-long-option-1: value
- // - positional-arg1
- // - positional-arg2
+ // - param-long-option-1: value
+ // - param-long-option-1: value
+ // - positional-arg1
+ // - positional-arg2
+ // two
+ // - param-long-option-1: value
+ // - param-long-option-1: value
+ // - positional-arg1
+ // - positional-arg2
try {
- Map<String, Object> values = (Map<String, Object>) new Yaml().load(FileUtils.readFileToString(new File(paramFilePath)));
+ Map<String, Object> values = (Map<String, Object>) OnapCommandDiscoveryUtils.loadYaml(paramFilePath);
for (Entry<String, Object> cmdsParam: values.entrySet()) {
List<String> args = new ArrayList<>();
}
}
+ public void verifyCommand(OnapCommand cmd) throws OnapCommandException {
+ List<Map<String, ?>> testSuite = OnapCommandRegistrar.getRegistrar().getTestSuite(cmd.getName());
+
+ OnapCommandResult testSuiteResult = new OnapCommandResult();
+ testSuiteResult.setType(OnapCommandResultType.TABLE);
+ testSuiteResult.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
+ testSuiteResult.setIncludeTitle(true);
+
+ OnapCommandResultAttribute sampleFileAtt = new OnapCommandResultAttribute();
+ OnapCommandResultAttribute sampleIdAtt = new OnapCommandResultAttribute();
+ OnapCommandResultAttribute resultAtt = new OnapCommandResultAttribute();
+
+ sampleFileAtt.setName("Test");
+ sampleIdAtt.setName("SampleId");
+ resultAtt.setName("Result");
+
+ testSuiteResult.setRecords(Arrays.asList(sampleFileAtt,
+ sampleIdAtt,
+ resultAtt));
+
+ for (Map<String, ?> sampleTest : testSuite) {
+
+ sampleFileAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_FILE_ID));
+ sampleIdAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_ID));
+
+ cmd = OnapCommandRegistrar.getRegistrar().get(args.get(0));
+ OnapCliArgsParser.populateParams(cmd.getParameters(), (List<String>) sampleTest.get(OnapCommandConstants.VERIFY_INPUT));
+
+
+ Optional<OnapCommandParameter> contextOpt = cmd.getParameters().stream()
+ .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
+ .findFirst();
+
+ if (contextOpt.isPresent()) {
+ HashMap map = new HashMap();
+ map.put(OnapCommandConstants.VERIFY_MOCO, sampleTest.get(OnapCommandConstants.VERIFY_MOCO));
+ contextOpt.get().setValue(map);
+ }
+
+ OnapCommandResult testResult = cmd.execute();
+ String actualOutput = testResult.print().trim();
+ String expectedOutput = (String) sampleTest.get(OnapCommandConstants.VERIFY_OUPUT);
+ expectedOutput = expectedOutput == null ? "" : expectedOutput.trim();
+
+ if (actualOutput.equals(expectedOutput)) {
+ resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_PASS);
+ } else {
+ resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_FAIL);
+ }
+ }
+ this.print(testSuiteResult.print());
+ }
/**
* Handles Interactive Mode.
*/
}
}
-
/**
* Handles command.
*/
this.exitFailure();
return;
}
+
try {
+
+ // verify
+ if(args.contains(OnapCommandConstants.VERIFY_LONG_OPTION)
+ || args.contains(OnapCommandConstants.VERIFY_SHORT_OPTION)) {
+ verifyCommand(cmd);
+ this.exitSuccessfully();
+ return;
+ }
// check for help or version
if (args.size() == 2) {
if (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(1))
*/
private ConsoleReader createConsoleReader() throws IOException {
ConsoleReader console = new ConsoleReader(); // NOSONAR
- try {
- StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion());
- strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT,
- OnapCliConstants.PARAM_INTERACTIVE_CLEAR,
- OnapCliConstants.PARAM_INTERACTIVE_USE,
- OnapCliConstants.PARAM_INTERACTIVE_HELP,
- OnapCliConstants.PARAM_INTERACTIVE_VERSION,
- OnapCliConstants.PARAM_INTERACTIVE_SET,
- OnapCliConstants.PARAM_INTERACTIVE_UNSET,
- OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
- console.addCompleter(strCompleter);
- console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT + ":" + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion() + ">");
- } catch (OnapCommandException e) { // NOSONAR
- this.print("Failed to load oclip commands," + e.getMessage());
- }
+ try {
+ StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion());
+ strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT,
+ OnapCliConstants.PARAM_INTERACTIVE_CLEAR,
+ OnapCliConstants.PARAM_INTERACTIVE_USE,
+ OnapCliConstants.PARAM_INTERACTIVE_HELP,
+ OnapCliConstants.PARAM_INTERACTIVE_VERSION,
+ OnapCliConstants.PARAM_INTERACTIVE_SET,
+ OnapCliConstants.PARAM_INTERACTIVE_UNSET,
+ OnapCliConstants.PARAM_INTERACTIVE_PROFILE);
+ console.addCompleter(strCompleter);
+ console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT + ":" + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion() + ">");
+ } catch (OnapCommandException e) { // NOSONAR
+ this.print("Failed to load oclip commands," + e.getMessage());
+ }
- return console;
+ return console;
}
System.exit(cli.getExitCode());
}
-}
+}
\ No newline at end of file
package org.onap.cli.main;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-
+import jline.console.ConsoleReader;
+import mockit.Invocation;
+import mockit.Mock;
+import mockit.MockUp;
import org.junit.Test;
+import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.error.OnapCommandHelpFailed;
import org.onap.cli.fw.registrar.OnapCommandRegistrar;
+import org.onap.cli.fw.schema.OnapCommandSchemaLoader;
-import jline.console.ConsoleReader;
-import mockit.Invocation;
-import mockit.Mock;
-import mockit.MockUp;
+import java.io.IOException;
+import java.util.List;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
public class OnapCliMainTest {
name: cloud-create
input: --cloud-name huawei-cloud --region-name bangalore
moco: cloud-create-schema-1.1-moco.json
- output: |
+ output:
-[ {
+[{
"request" : {
"method" : "get",
"uri" : "/aai/v11/cloud-infrastructure/cloud-regions",
} ]
}
}
-} ]
\ No newline at end of file
+}]
\ No newline at end of file
<version>1.19</version>
<scope>test</scope>
</dependency>
- </dependencies>
+ <dependency>
+ <groupId>com.github.dreamhead</groupId>
+ <artifactId>moco-runner</artifactId>
+ <version>0.12.0</version>
+ <exclusions>
+ <exclusion>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ </dependencies>
<build>
<plugins>
<plugin>
package org.onap.cli.fw.http.cmd;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.cmd.OnapCommandType;
import org.onap.cli.fw.conf.OnapCommandConfig;
import org.onap.cli.fw.http.connect.HttpInput;
import org.onap.cli.fw.http.connect.HttpResult;
import org.onap.cli.fw.http.error.OnapCommandFailedMocoGenerate;
+import org.onap.cli.fw.http.mock.MocoServer;
import org.onap.cli.fw.http.schema.OnapCommandSchemaHttpLoader;
import org.onap.cli.fw.http.utils.OnapCommandHttpUtils;
+import org.onap.cli.fw.input.OnapCommandParameter;
import org.onap.cli.fw.output.OnapCommandResultAttribute;
import org.onap.cli.fw.schema.OnapCommandSchema;
import org.onap.cli.fw.utils.OnapCommandUtils;
import org.onap.cli.http.mock.MockRequest;
import org.onap.cli.http.mock.MockResponse;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+
/**
* Oclip http Command.
*
private OnapCommandHttpService oclipService = new OnapCommandHttpService();
+ private MocoServer mocoServer;
+
+ boolean shouldVerify = false;
+
public OnapHttpCommand() {
super.addDefaultSchemas(OnapCommandHttpConstants.DEFAULT_PARAMETER_HTTP_FILE_NAME);
}
this.getInfo().getCommandType().equals(OnapCommandType.CATALOG));
}
+ private Optional<OnapCommandParameter> findParameterByName(String parameterName) {
+ return this.getParameters().stream()
+ .filter(e -> e.getName().equals(parameterName))
+ .findFirst();
+ }
+
+ @Override
+ protected void preRun() throws OnapCommandException {
+ Optional<OnapCommandParameter> verifyOpt = this.getParameters().stream()
+ .filter(e -> e.getName().equals("verify"))
+ .findFirst();
+ if(verifyOpt.isPresent()) {
+ shouldVerify = (boolean) verifyOpt.get().getValue();
+ }
+
+ if (shouldVerify) {
+ Optional<OnapCommandParameter> hostUrlParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_HOST_PARAMETER_OPT);
+ Optional<OnapCommandParameter> noAuthParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_NO_AUTH_PARAMETER_OPT);
+
+ if (hostUrlParamOpt.isPresent()) {
+ OnapCommandParameter onapCommandParameter = hostUrlParamOpt.get();
+ onapCommandParameter.setValue(
+ OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_HOST)
+ + ":" + OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_PORT));
+ }
+
+ if (noAuthParamOpt.isPresent()) {
+ OnapCommandParameter onapCommandParameter = noAuthParamOpt.get();
+ onapCommandParameter.setValue(true);
+ }
+
+
+ Optional<OnapCommandParameter> contextOpt = this.getParameters().stream()
+ .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
+ .findFirst();
+
+ if (contextOpt.isPresent()) {
+ OnapCommandParameter context = contextOpt.get();
+ String mockedFile = ((Map<String, String>)context.getValue()).get(OnapCommandConstants.VERIFY_MOCO);
+
+ mocoServer = new MocoServer(mockedFile);
+ mocoServer.start();
+ }
+ }
+ }
+
+ @Override
+ protected void postRun() throws OnapCommandException {
+ if (shouldVerify) {
+ mocoServer.stop();
+ }
+ }
+
@Override
protected void run() throws OnapCommandException {
try {
//context param
public static final String CONTEXT = "context";
public static final String CONTEXT_REMOVE_EMPTY_JSON_NODES = "remove_empty_node";
+
+ // moco server const
+ public static final String VERIFY_MOCO_HOST = "cli.verify.host";
+ public static final String VERIFY_MOCO_PORT = "cli.verify.port";
+
+ public static final String VERIFY_HOST_PARAMETER_OPT = DEAFULT_PARAMETER_HOST_URL;
+ public static final String VERIFY_NO_AUTH_PARAMETER_OPT = DEFAULT_PARAMETER_NO_AUTH;
+
+ public static final String VERIFY_REQUEST_URI = URI;
+ public static final String VERIFY_RESPONSE_STATUS = "status";
+ public static final String VERIFY_RESPONSE_JSON = "json";
+ public static final String VERIFY_REQUEST = REQUEST;
+ public static final String VERIFY_RESPONSE = "response";
+ public static final String VERIFY_CONTENT_TYPE = "Content-Type";
+ public static final String VERIFY_CONTENT_TYPE_VALUE = APPLICATION_JSON;
}
--- /dev/null
+/*
+ * Copyright 2017 Huawei Technologies Co., Ltd.
+ *
+ * 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.cli.fw.http.mock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.dreamhead.moco.HttpServer;
+import com.github.dreamhead.moco.Moco;
+import com.github.dreamhead.moco.ResponseHandler;
+import com.github.dreamhead.moco.Runner;
+import org.onap.cli.fw.conf.OnapCommandConfig;
+import org.onap.cli.fw.conf.OnapCommandConstants;
+import org.onap.cli.fw.error.OnapCommandDiscoveryFailed;
+import org.onap.cli.fw.error.OnapCommandException;
+import org.onap.cli.fw.error.OnapCommandInvalidSchema;
+import org.onap.cli.fw.http.conf.OnapCommandHttpConstants;
+import org.onap.cli.fw.schema.OnapCommandSchemaLoader;
+import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
+import org.springframework.core.io.Resource;
+import org.yaml.snakeyaml.Yaml;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static com.github.dreamhead.moco.Runner.runner;
+
+public class MocoServer {
+
+ private Runner runner;
+ private Map<String, Object> mocoServerConfigs = new HashMap();
+
+ public MocoServer(String mockFile) throws OnapCommandException {
+ Resource resource = null;
+
+ try {
+ resource = OnapCommandDiscoveryUtils.findResource(mockFile,
+ OnapCommandConstants.VERIFY_SAMPLES_MOCK_PATTERN);
+ } catch (IOException e) {
+ throw new OnapCommandDiscoveryFailed(mockFile, e);
+ }
+
+ List<Map<String, ?>> stringMap = null;
+ try {
+ stringMap = (List<Map<String, ?>>) new Yaml().load(resource.getInputStream());
+ } catch (IOException e) {
+ throw new OnapCommandException("Invalid mocking file" + mockFile, e);
+ }
+ if(!stringMap.isEmpty()) {
+ Map<String, ?> jsonConfigs = stringMap.get(0);
+ Map<String, String> request = (Map<String, String>) jsonConfigs.get(OnapCommandHttpConstants.VERIFY_REQUEST);
+ mocoServerConfigs.put(OnapCommandHttpConstants.VERIFY_REQUEST_URI, request.get(OnapCommandHttpConstants.VERIFY_REQUEST_URI));
+
+ Map<String, String> response = (Map<String, String>) jsonConfigs.get(OnapCommandHttpConstants.VERIFY_RESPONSE);
+ mocoServerConfigs.put(OnapCommandHttpConstants.VERIFY_RESPONSE_STATUS, response.get(OnapCommandHttpConstants.VERIFY_RESPONSE_STATUS));
+
+ if(response.get(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON) != null) {
+ try {
+ mocoServerConfigs.put(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON,
+ new ObjectMapper().writeValueAsString(response.get(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON)));
+ } catch (JsonProcessingException e) {
+ throw new OnapCommandException("Invalid mocking file" + mockFile, e);
+ }
+ }
+ }
+ }
+
+ public void start() {
+ HttpServer server = Moco.httpServer(Integer.parseInt(
+ OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_PORT)));
+
+ List<ResponseHandler> responseHandlers = new ArrayList<>();
+
+ if (mocoServerConfigs.containsKey(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON)) {
+ responseHandlers.add(Moco.with(mocoServerConfigs.get(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON).toString()));
+ }
+ responseHandlers.add(Moco.status((Integer) mocoServerConfigs.get(OnapCommandHttpConstants.VERIFY_RESPONSE_STATUS)));
+
+ server.request(Moco.by(Moco.uri((String) mocoServerConfigs.get(OnapCommandHttpConstants.VERIFY_REQUEST_URI))))
+ .response(Moco.header(OnapCommandHttpConstants.VERIFY_CONTENT_TYPE, OnapCommandHttpConstants.VERIFY_CONTENT_TYPE_VALUE),
+ responseHandlers.toArray(new ResponseHandler[responseHandlers.size()]));
+
+ runner = runner(server);
+ runner.start();
+ }
+
+ public void stop() {
+ runner.stop();
+ }
+}
cli.schema.http.service.auth.values=none,basic
cli.schema.http.service.mode.values=direct,catalog
+
+#verify properties
+cli.verify.host=http://localhost
+cli.verify.port=8585
\ No newline at end of file
long_option: no-catalog
is_optional: true
is_default_param: true
- default_value: false
\ No newline at end of file
+ default_value: false
+ - name: verify
+ type: bool
+ description: verify the command using available command sample file and mocking file
+ default_value: false
+ is_include: true
+ is_optional: true
\ No newline at end of file
assertTrue("sample-test".equals(cmd.getName()));
Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters());
- assertTrue(map.size() == 8);
+ assertTrue(map.size() == 9);
}
@Test(expected = OnapCommandHttpHeaderNotFound.class)
<name>cli/validate/validation</name>
<packaging>jar</packaging>
<dependencies>
- <dependency>
- <groupId>com.github.dreamhead</groupId>
- <artifactId>moco-runner</artifactId>
- <version>0.11.1</version>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<artifactId>cli-products-onap-amsterdam-features-aai</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.6</version>
+ </dependency>
</dependencies>
<!-- <build>
<plugins>
+++ /dev/null
-/*
- * Copyright 2017 Huawei Technologies Co., Ltd.
- *
- * 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.cli.moco;
-
-import static com.github.dreamhead.moco.Moco.pathResource;
-import static com.github.dreamhead.moco.MocoJsonRunner.jsonHttpServer;
-import static com.github.dreamhead.moco.Runner.runner;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-
-import org.onap.cli.fw.error.OnapCommandException;
-import org.onap.cli.fw.error.OnapCommandInvalidSample;
-import org.onap.cli.fw.registrar.OnapCommandRegistrar;
-import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
-import org.onap.cli.main.OnapCli;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.core.io.Resource;
-import org.yaml.snakeyaml.Yaml;
-
-import com.github.dreamhead.moco.HttpServer;
-import com.github.dreamhead.moco.Runner;
-
-public class OnapCommandHttpMocoServer {
-
- public static final String SAMPLE_PATTERN = "onap-cli-sample/**/";
-
- public static final String SAMPLE_VERSION = "open_cli_sample_version";
- public static final String SAMPLE_VERSION_1_0 = "1.0";
-
- public static final String SAMPLE_COMMAND_NAME = "name";
- public static final String SAMPLE_PRODUCT = "version";
- public static final String SAMPLE_LIST = "samples";
- public static final String SAMPLE_DESCRIPTION = "name";
- public static final String SAMPLE_INPUT = "input";
- public static final String SAMPLE_OUTPUT = "output";
- public static final String SAMPLE_MOCO = "moco";
-
- private static Logger LOG = LoggerFactory.getLogger(OnapCommandHttpMocoServer.class);
-
- private String samplesToTest = "*.yaml";
-
- private int port = 8141;
-
- public int getPort() {
- return port;
- }
-
- public void setPort(int port) {
- this.port = port;
- }
-
- public OnapCommandHttpMocoServer(String samplesToTest) {
- this.samplesToTest = samplesToTest;
- }
-
- public OnapCommandHttpMocoServer() {
- }
-
- public static Map<String, List<OnapCommandSample>> discoverYamls(File path) throws IOException {
- Map<String, List<OnapCommandSample>> cliProductSamples = new HashMap<>();
-
- Stream<Path> walk = Files.walk(path.toPath());
- walk.filter(p -> (p.toString().contains("src/test/resources/onap-cli-sample")))
- .filter(p -> p.toString().endsWith("sample.yaml"))
- .forEach(p -> {
- collectSamples(new File(p.toUri()), cliProductSamples);
- });
-
- return cliProductSamples;
- }
-
- private static void collectSamples(File file, Map<String, List<OnapCommandSample>> result) {
- OnapCommandHttpMocoServer onapCommandHttpMocoServer = new OnapCommandHttpMocoServer();
- List<OnapCommandSample> loadSamples;
- try {
- loadSamples = onapCommandHttpMocoServer.loadSamples(file);
- loadSamples.stream().forEach(sample -> {
- if (!result.containsKey(sample.getProduct())) {
- result.put(sample.getProduct(), new ArrayList<>());
- }
- result.get(sample.getProduct()).add(sample);
- });
- } catch (OnapCommandInvalidSample e) {
- LOG.error("Failed to read sample file", e);
- }
- }
-
- private List<Resource> dicoverSampleYamls() {
- Resource[] resources = new Resource [] {};
- try {
- resources = OnapCommandDiscoveryUtils.findResources(SAMPLE_PATTERN + this.samplesToTest);
- } catch (IOException e) {
- LOG.error("Failed to discover the samples", e);
- }
-
- return Arrays.asList(resources);
- }
-
- private String getValue(Map<String, ?> map, String prpName) {
- Object o = map.get(prpName);
- if (o != null) {
- return o.toString();
- }
-
- return "";
- }
-
- public List<OnapCommandSample> loadSamples(InputStream inputStream, String fileName) throws OnapCommandInvalidSample {
- List<OnapCommandSample> samples = new ArrayList<>();
- Map<String, ?> values = null;
- try {
- values = (Map<String, ?>) new Yaml().load(inputStream);
- } catch (Exception e) {
- throw new OnapCommandInvalidSample(fileName, e);
- }
-
- OnapCommandSample sample = new OnapCommandSample();
-
- if (!this.getValue(values, SAMPLE_VERSION).equals(SAMPLE_VERSION_1_0)) {
- throw new OnapCommandInvalidSample(fileName, "Invalid sample version " + this.getValue(values, SAMPLE_VERSION));
- }
-
- sample.setCommandName(this.getValue(values, SAMPLE_COMMAND_NAME));
- sample.setProduct(this.getValue(values, SAMPLE_PRODUCT));
-
- //Retrieve the samples
- values = (Map<String, Map<String, String>>) values.get(SAMPLE_LIST);
-
- for (String s: values.keySet()) {
- Map<String, ?> sMap = (Map<String, ?>)values.get(s);
- sample.setDescription(this.getValue(sMap, SAMPLE_DESCRIPTION));
- sample.setInput(this.getValue(sMap, SAMPLE_INPUT));
- sample.setOutput(this.getValue(sMap, SAMPLE_OUTPUT));
- sample.setMoco(this.getValue(sMap, SAMPLE_MOCO));
- samples.add(sample);
- }
-
- return samples;
- }
-
- public List<OnapCommandSample> loadSamples(Resource file) throws OnapCommandInvalidSample {
- try {
- return loadSamples(file.getInputStream(), file.getFilename());
- } catch (IOException e) {
- throw new OnapCommandInvalidSample(file.getFilename(), e);
- }
- }
-
- public List<OnapCommandSample> loadSamples(File file) throws OnapCommandInvalidSample {
- try {
- return loadSamples(new FileInputStream(file), file.getName());
- } catch (FileNotFoundException e) {
- throw new OnapCommandInvalidSample(file.getName(), e);
- }
- }
- private void verifySample(OnapCommandSample sample) throws OnapCommandException {
-
- List <String> args = new ArrayList<>();
- args.add(sample.getCommandName());
- args.addAll(Arrays.asList(sample.getInput().split(" ")));
-
- ByteArrayOutputStream bo = new ByteArrayOutputStream();
- System.setOut(new PrintStream(bo));
-
- OnapCli cli = new OnapCli(args.toArray(new String []{}));
- OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(sample.getProduct());
- cli.handle();
-
- String output = new String(bo.toByteArray());
-
- assert cli.getExitCode() == 0;
-
- assert sample.getOutput().equals(output);
- }
-
- public void verifySamples() throws OnapCommandException {
- for (Resource rsc : this.dicoverSampleYamls()) {
- for(OnapCommandSample sample: this.loadSamples(rsc)) {
-
- if (!sample.getMoco().isEmpty()) {
- HttpServer server = jsonHttpServer(this.getPort(), pathResource(sample.getMoco()));
- Runner r = runner(server);
- r.start();
-
- this.verifySample(sample);
-
- r.stop();
- }
- }
- }
- }
-}
\ No newline at end of file
package org.onap.cli.validation;
-import static org.junit.Assert.fail;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
import org.apache.commons.io.FileUtils;
-import org.junit.Ignore;
import org.junit.Test;
+import org.onap.cli.fw.conf.OnapCommandConstants;
import org.onap.cli.fw.error.OnapCommandException;
+import org.onap.cli.fw.error.OnapCommandInvalidSample;
import org.onap.cli.fw.registrar.OnapCommandRegistrar;
import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
import org.onap.cli.main.OnapCli;
-import org.onap.cli.moco.OnapCommandHttpMocoServer;
+import org.onap.cli.main.conf.OnapCliConstants;
import org.onap.cli.moco.OnapCommandSample;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.Yaml;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
public class OnapValidationTest {
+ public static final String SAMPLE_VERSION = "open_cli_sample_version";
+ public static final String SAMPLE_VERSION_1_0 = "1.0";
+
+ public static final String SAMPLE_COMMAND_NAME = "name";
+ public static final String SAMPLE_PRODUCT = "version";
+ public static final String SAMPLE_LIST = "samples";
+ public static final String SAMPLE_DESCRIPTION = "name";
+ public static final String SAMPLE_INPUT = "input";
+ public static final String SAMPLE_OUTPUT = "output";
+ public static final String SAMPLE_MOCO = "moco";
+
OnapCli cli = null;
+ private static Logger LOG = LoggerFactory.getLogger(OnapValidationTest.class);
+
private void handle(String[] args) {
cli = new OnapCli(args);
cli.handle();
}
}
- @Ignore
- @Test
- public void verifyCommandResults() throws OnapCommandException {
- OnapCommandHttpMocoServer server = new OnapCommandHttpMocoServer();
- server.verifySamples();
- }
-
@Test
public void collectSampleYamlTest() {
try {
String sampleFileName = "target/sample.rst";
FileUtils.deleteQuietly(new File(sampleFileName));
- Map<String, List<OnapCommandSample>> discoveredYamls = OnapCommandHttpMocoServer.discoverYamls(root);
+ Map<String, List<OnapCommandSample>> discoveredYamls = discoverYamls(root);
writeSamples(new File(sampleFileName), discoveredYamls);
} catch (IOException e) {
}
}
+ public static Map<String, List<OnapCommandSample>> discoverYamls(File path) throws IOException {
+ Map<String, List<OnapCommandSample>> cliProductSamples = new HashMap<>();
+
+ Stream<Path> walk = Files.walk(path.toPath());
+ walk.filter(p -> (p.toString().contains("src/test/resources/onap-cli-sample")))
+ .filter(p -> p.toString().endsWith("sample.yaml"))
+ .forEach(p -> {
+ collectSamples(new File(p.toUri()), cliProductSamples);
+ });
+
+ return cliProductSamples;
+ }
+
+ private static void collectSamples(File file, Map<String, List<OnapCommandSample>> result) {
+ List<OnapCommandSample> loadSamples;
+ try {
+ loadSamples = loadSamples(file);
+ loadSamples.stream().forEach(sample -> {
+ if (!result.containsKey(sample.getProduct())) {
+ result.put(sample.getProduct(), new ArrayList<>());
+ }
+ result.get(sample.getProduct()).add(sample);
+ });
+ } catch (OnapCommandInvalidSample e) {
+ LOG.error("Failed to read sample file", e);
+ }
+ }
+
+ private static List<OnapCommandSample> loadSamples(File file) throws OnapCommandInvalidSample {
+ try {
+ return loadSamples(new FileInputStream(file), file.getName());
+ } catch (FileNotFoundException e) {
+ throw new OnapCommandInvalidSample(file.getName(), e);
+ }
+ }
+
+ private static List<OnapCommandSample> loadSamples(InputStream inputStream, String fileName) throws OnapCommandInvalidSample {
+ List<OnapCommandSample> samples = new ArrayList<>();
+ Map<String, ?> values = null;
+ try {
+ values = (Map<String, ?>) new Yaml().load(inputStream);
+ } catch (Exception e) {
+ throw new OnapCommandInvalidSample(fileName, e);
+ }
+
+ OnapCommandSample sample = new OnapCommandSample();
+
+ if (!getValue(values, SAMPLE_VERSION).equals(SAMPLE_VERSION_1_0)) {
+ throw new OnapCommandInvalidSample(fileName, "Invalid sample version " + getValue(values, SAMPLE_VERSION));
+ }
+
+ sample.setCommandName(getValue(values, SAMPLE_COMMAND_NAME));
+ sample.setProduct(getValue(values, SAMPLE_PRODUCT));
+
+ //Retrieve the samples
+ values = (Map<String, Map<String, String>>) values.get(SAMPLE_LIST);
+
+ for (String s: values.keySet()) {
+ Map<String, ?> sMap = (Map<String, ?>)values.get(s);
+ sample.setDescription(getValue(sMap, SAMPLE_DESCRIPTION));
+ sample.setInput(getValue(sMap, SAMPLE_INPUT));
+ sample.setOutput(getValue(sMap, SAMPLE_OUTPUT));
+ sample.setMoco(getValue(sMap, SAMPLE_MOCO));
+ samples.add(sample);
+ }
+
+ return samples;
+ }
+
+ private static String getValue(Map<String, ?> map, String prpName) {
+ Object o = map.get(prpName);
+ if (o != null) {
+ return o.toString();
+ }
+
+ return "";
+ }
+
+ @Test
+ public void testVerify() throws OnapCommandException {
+ OnapCommandRegistrar.getRegistrar().setEnabledProductVersion("open-cli");
+ OnapCli onapCli = new OnapCli(new String[]{"sample-test-verify", "--verify"});
+ onapCli.handle();
+ assertEquals(OnapCliConstants.EXIT_SUCCESS, onapCli.getExitCode());
+ }
}
--- /dev/null
+[{
+ "request" : {
+ "method" : "get",
+ "uri" : "/aai/v11/cloud-infrastructure/cloud-regions",
+ "headers" : {
+ "Authorization" : "Basic QUFJOkFBSQ==",
+ "X-FromAppId" : "onap-cli",
+ "Accept" : "application/json",
+ "X-TransactionId" : "req-77c08aa0-662e-4d32-9206-bd569c3bf61b",
+ "Content-Type" : "application/json"
+ },
+ "json" : null
+ },
+ "response" : {
+ "status" : 200,
+ "json" : {
+ "cloud-region" : [ {
+ "cloud-owner" : "huawei-cloud",
+ "cloud-region-id" : "bangalore",
+ "sriov-automation" : false,
+ "resource-version" : "1509027332165"
+ }, {
+ "cloud-owner" : "Rackspace",
+ "cloud-region-id" : "RegionOne",
+ "cloud-type" : "SharedNode",
+ "owner-defined-type" : "OwnerType",
+ "cloud-region-version" : "v1",
+ "cloud-zone" : "CloudZone",
+ "sriov-automation" : false,
+ "resource-version" : "1508827902543"
+ } ]
+ }
+ }
+}]
\ No newline at end of file
--- /dev/null
+# Copyright 2017-18 Huawei Technologies Co., Ltd.
+#
+# 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.
+
+open_cli_sample_version: 1.0
+name: sample-test-verify
+version: open-cli
+samples:
+ sample1:
+ name: sample-test-verify
+ input:
+ moco: sample-test-verify-schema-1.1-moco.json
+ output: |
+ +--------------+------------+------------------+
+ |cloud |region |resource-version |
+ +--------------+------------+------------------+
+ |huawei-cloud |bangalore |1509027332165 |
+ +--------------+------------+------------------+
+ |Rackspace |RegionOne |1508827902543 |
+ +--------------+------------+------------------+
+
+ sample2:
+ name: sample-test-verify
+ input:
+ moco: sample-test-verify-schema-1.1-moco.json
+ output: |
+ +--------------+------------+------------------+
+ |cloud |region |resource-version |
+ +--------------+------------+------------------+
+ |huawei-cloud |bangalore |1509027332165 |
+ +--------------+------------+------------------+
+ |Rackspace |RegionOne |1508827902543 |
+ +--------------+------------+------------------+
--- /dev/null
+# Copyright 2017-18 Huawei Technologies Co., Ltd.
+#
+# 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.
+
+open_cli_schema_version: 1.0
+name: sample-test-verify
+description: Oclip sample command to test the command features
+info:
+ product: open-cli
+ service: test
+ type: cmd
+
+results:
+ direction: landscape
+ attributes:
+ - name: cloud
+ description: Onap cloud
+ scope: short
+ type: string
+ - name: region
+ description: Onap cloud region
+ scope: short
+ type: string
+ - name: tenant
+ description: Onap cloud tenat
+ scope: long
+ type: string
+ - name: tenant-id
+ description: Onap cloud tenat id
+ scope: long
+ type: string
+ - name: customer
+ description: Onap cloud customer
+ scope: long
+ type: string
+ - name: service
+ description: Onap cloud service
+ scope: long
+ type: string
+ - name: resource-version
+ description: Onap cloud resource version
+ scope: short
+ type: string
+http:
+ service:
+ auth: basic
+ mode: direct
+ request:
+ uri: /aai/v11/cloud-infrastructure/cloud-regions
+ method: GET
+ success_codes:
+ - 200
+ result_map:
+ cloud: $b{cloud-region.[*].cloud-owner}
+ region: $b{cloud-region.[*].cloud-region-id}
+ resource-version: $b{cloud-region.[*].resource-version}
+ tenant: $b{cloud-region.[*].tenants.tenant.[*].tenant-name}
+ tenant-id: $b{cloud-region.[*].tenants.tenant.[*].tenant-id}
+ customer: $b{cloud-region.[*].tenants.tenant.[*].relationship-list.relationship.[*].relationship-data.[?(@.relationship-key == 'customer.global-customer-id')].relationship-value}
+ service: $b{cloud-region.[*].tenants.tenant.[*].relationship-list.relationship.[*].relationship-data.[?(@.relationship-key == 'service-subscription.service-type')].relationship-value}
+ sample_response:
+ body: '{"cloud-region":[{"cloud-owner":"Rackspace","cloud-region-id":"RegionOne","cloud-type":"SharedNode","owner-defined-type":"OwnerType","cloud-region-version":"v1","cloud-zone":"CloudZone","resource-version":"1500729864","tenants":{"tenant":[{"tenant-id":"e69e6d64b44347509c3fc512391f34a6","tenant-name":"onap","resource-version":"1500729865","relationship-list":{"relationship":[{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration123/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration123"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/u1/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"u1"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/u2/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"u2"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/DemoCust_7151e36a-1a57-4993-b513-54134f2b8f19/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"DemoCust_7151e36a-1a57-4993-b513-54134f2b8f19"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vLB/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration"},{"relationship-key":"service-subscription.service-type","relationship-value":"vLB"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Linan/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Linan"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Linan/service-subscriptions/service-subscription/vLB/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Linan"},{"relationship-key":"service-subscription.service-type","relationship-value":"vLB"}]}]}}]}}]}'