diff options
author | Kanagaraj Manickam k00365106 <kanagaraj.manickam@huawei.com> | 2017-07-19 15:14:29 +0530 |
---|---|---|
committer | Kanagaraj Manickam k00365106 <kanagaraj.manickam@huawei.com> | 2017-07-19 15:31:19 +0530 |
commit | b610d2dbfa445e2ed8fd7f9976ae7a776666d630 (patch) | |
tree | 6d58385dc197aada4c6a832c922f04d0f4da61ad /framework/src/test/java/org/onap | |
parent | 20173579de1cd7d8f70fc2cdf17a4f9c0fc6e946 (diff) |
Add seed code from Open-Orelease-1.0.0
It migrated the code from Open-O into
onap namespace and adds the required
framework, main, deployment and some
sample plugins for msb.
CLI-7
CLI-8
CLI-11
Change-Id: I499e34237daccb971ef74bd10e50f50707baa4d3
Signed-off-by: Kanagaraj Manickam k00365106 <kanagaraj.manickam@huawei.com>
Diffstat (limited to 'framework/src/test/java/org/onap')
37 files changed, 3625 insertions, 0 deletions
diff --git a/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java new file mode 100644 index 00000000..69714ad7 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java @@ -0,0 +1,47 @@ +/* + * 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.cmd.sample; + +import org.onap.cli.fw.OnapCommand; +import org.onap.cli.fw.OnapCommandSchema; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; + +/** + * This command helps to test the Command functionalities. + * + */ +@OnapCommandSchema(name = "sample-test", schema = "sample-test-schema.yaml") +public class OnapCommandSample extends OnapCommand { + + public OnapCommandSample() { + this(true); + } + + public OnapCommandSample(boolean isInit) { + this.isInitialzied = isInit; + } + + public boolean failCase = false; + + @Override + protected void run() throws OnapCommandException { + if (this.failCase) + throw new OnapCommandExecutionFailed("Test case to fail"); + } + +} diff --git a/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java new file mode 100644 index 00000000..9cf6bdf5 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java @@ -0,0 +1,157 @@ +/* + * 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.cmd.sample; + +import org.junit.Test; +import org.onap.cli.fw.conf.Constants; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.error.OnapCommandNotInitialized; +import org.onap.cli.fw.input.OnapCommandParameter; +import org.onap.cli.fw.input.ParameterType; + +import java.util.ArrayList; +import java.util.List; + +public class OnapCommandSampleTest { + @Test + public void sampleTestVersion() { + OnapCommandSample sample = new OnapCommandSample(); + + try { + List<OnapCommandParameter> parameters = new ArrayList(); + OnapCommandParameter v = new OnapCommandParameter(); + v.setName(Constants.DEFAULT_PARAMETER_VERSION); + v.setValue("true"); + parameters.add(v); + OnapCommandParameter h = new OnapCommandParameter(); + h.setName(Constants.DEFAULT_PARAMETER_HELP); + h.setValue("false"); + parameters.add(h); + sample.setParameters(parameters); + sample.execute(); + } catch (OnapCommandException e) { + } + } + + @Test + public void sampleTestHelp() { + OnapCommandSample sample = new OnapCommandSample(); + try { + List<OnapCommandParameter> parameters = new ArrayList(); + OnapCommandParameter v = new OnapCommandParameter(); + v.setName(Constants.DEFAULT_PARAMETER_HELP); + v.setValue("true"); + v.setParameterType(ParameterType.BOOL); + parameters.add(v); + sample.setParameters(parameters); + sample.execute(); + } catch (OnapCommandException e) { + } + } + + @Test + public void sampleTest() { + OnapCommandSample sample = new OnapCommandSample(); + try { + List<OnapCommandParameter> parameters = new ArrayList(); + OnapCommandParameter v = new OnapCommandParameter(); + v.setName(Constants.DEFAULT_PARAMETER_VERSION); + v.setValue("false"); + parameters.add(v); + OnapCommandParameter h = new OnapCommandParameter(); + h.setName(Constants.DEFAULT_PARAMETER_HELP); + h.setValue("false"); + parameters.add(h); + OnapCommandParameter f = new OnapCommandParameter(); + f.setName(Constants.DEFAULT_PARAMETER_OUTPUT_FORMAT); + f.setValue("table"); + parameters.add(f); + OnapCommandParameter l = new OnapCommandParameter(); + l.setName(Constants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); + l.setValue("true"); + parameters.add(l); + OnapCommandParameter t = new OnapCommandParameter(); + t.setName(Constants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); + t.setValue("true"); + parameters.add(t); + OnapCommandParameter a = new OnapCommandParameter(); + a.setName(Constants.DEFAULT_PARAMETER_OUTPUT_NO_AUTH); + a.setValue("true"); + parameters.add(a); + OnapCommandParameter d = new OnapCommandParameter(); + d.setName(Constants.DEFAULT_PARAMETER_DEBUG); + d.setValue("true"); + parameters.add(d); + OnapCommandParameter m = new OnapCommandParameter(); + m.setName(Constants.DEAFULT_PARAMETER_MSB_URL); + m.setValue("http://localhost"); + parameters.add(m); + sample.setParameters(parameters); + sample.execute(); + } catch (OnapCommandException e) { + } + } + + @Test(expected = OnapCommandExecutionFailed.class) + public void sampleTestFailure() throws OnapCommandException { + OnapCommandSample sample = new OnapCommandSample(); + sample.failCase = true; + + List<OnapCommandParameter> parameters = new ArrayList(); + OnapCommandParameter v = new OnapCommandParameter(); + v.setName(Constants.DEFAULT_PARAMETER_VERSION); + v.setValue("false"); + parameters.add(v); + OnapCommandParameter h = new OnapCommandParameter(); + h.setName(Constants.DEFAULT_PARAMETER_HELP); + h.setValue("false"); + parameters.add(h); + OnapCommandParameter f = new OnapCommandParameter(); + f.setName(Constants.DEFAULT_PARAMETER_OUTPUT_FORMAT); + f.setValue("table"); + parameters.add(f); + OnapCommandParameter l = new OnapCommandParameter(); + l.setName(Constants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); + l.setValue("true"); + parameters.add(l); + OnapCommandParameter t = new OnapCommandParameter(); + t.setName(Constants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); + t.setValue("true"); + parameters.add(t); + OnapCommandParameter a = new OnapCommandParameter(); + a.setName(Constants.DEFAULT_PARAMETER_OUTPUT_NO_AUTH); + a.setValue("true"); + parameters.add(a); + OnapCommandParameter d = new OnapCommandParameter(); + d.setName(Constants.DEFAULT_PARAMETER_DEBUG); + d.setValue("true"); + parameters.add(d); + OnapCommandParameter m = new OnapCommandParameter(); + m.setName(Constants.DEAFULT_PARAMETER_MSB_URL); + m.setValue("http://localhost"); + parameters.add(m); + sample.setParameters(parameters); + sample.execute(); + } + + @Test(expected = OnapCommandNotInitialized.class) + public void sampleTestIsInitialized() throws OnapCommandException { + OnapCommandSample sample = new OnapCommandSample(false); + sample.execute(); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java b/framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java new file mode 100644 index 00000000..83f3a743 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java @@ -0,0 +1,170 @@ +/* + * 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; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandHelpFailed; +import org.onap.cli.fw.error.OnapCommandNotFound; +import org.onap.cli.fw.error.OnapCommandRegistrationFailed; + +import java.io.File; +import java.net.URL; + +public class OnapCommandRegistrarTest { + + OnapCommandRegistrar registerar; + + @Before + public void setup() throws OnapCommandException { + registerar = OnapCommandRegistrar.getRegistrar(); + createDir(); + } + + private void createDir() { + URL url = OnapCommandRegistrarTest.class.getClassLoader().getResource("onap-cli-schema"); + if (url != null) { + String path = url.getPath(); + path = path.replaceFirst("onap-cli-schema", "data"); + File file = new File(path); + if (!file.exists()) { + file.mkdir(); + } else { + File f1 = new File(path + "/external-schema.json"); + f1.delete(); + } + } + } + + @Test + public void registerTest() throws OnapCommandException { + OnapCommand test = new OnapCommandTest(); + Class<OnapCommand> cmd = (Class<OnapCommand>) test.getClass(); + registerar.register("Test", cmd); + OnapCommand cc = registerar.get("Test"); + assertTrue(cmd == cc.getClass()); + + } + + @Test + // For Coverage + public void cmdTestSchema() throws OnapCommandException { + OnapCommand test = new OnapCommandTest(); + Class<OnapCommand> cmd = (Class<OnapCommand>) test.getClass(); + registerar.register("Test", cmd); + OnapCommand cc = registerar.get("Test"); + } + + @Test + public void onapCommandNotFoundTest() throws OnapCommandException { + try { + registerar = OnapCommandRegistrar.getRegistrar(); + registerar.get("Test1"); + fail("This should have thrown an exception"); + } catch (OnapCommandNotFound e) { + assertEquals(e.getMessage(), "0x0011::Command Test1 is not registered"); + } + } + + @Test + public void onapCommandRegistrationFailedTest() throws OnapCommandException { + + @OnapCommandSchema(name = "Test2", schema = "sample-test-schema.yaml") + class Test extends OnapCommand { + + @Override + protected void run() throws OnapCommandException { + + } + + } + + OnapCommand com = new Test(); + Class<OnapCommand> cmd = (Class<OnapCommand>) com.getClass(); + try { + registerar.register("Test2", cmd); + registerar.get("Test2"); + fail("This should have thrown an exception"); + } catch (OnapCommandRegistrationFailed e) { + assertTrue(e.getMessage().contains("0x0018::Command Test2 is failed to register")); + } + } + + @Test(expected = OnapCommandHelpFailed.class) + // For coverage + public void helpTestException() throws OnapCommandException { + OnapCommand test = new OnapCommandTest1(); + Class<OnapCommand> cmd = (Class<OnapCommand>) test.getClass(); + registerar = new OnapCommandRegistrar(); + registerar.register("test1", cmd); + String help = registerar.getHelp(); + assertNotNull(help); + } + + @Test + public void helpTest() throws OnapCommandException { + String help = registerar.getHelp(); + assertNotNull(help); + } + + @Test + public void versionTest() throws OnapCommandHelpFailed { + String version = registerar.getVersion(); + assertNotNull(version); + } + + @Test + public void listTest() { + registerar.listCommands(); + } +} + +@OnapCommandSchema(name = OnapCommandTest.CMD_NAME, schema = "sample-test-schema.yaml") +class OnapCommandTest extends OnapCommand { + + public OnapCommandTest() { + + } + + public static final String CMD_NAME = "test"; + + protected void run() throws OnapCommandException { + + } + +} + +@OnapCommandSchema(name = OnapCommandTest1.CMD_NAME, schema = "test-schema.yaml") +class OnapCommandTest1 extends OnapCommand { + + public OnapCommandTest1() { + + } + + public static final String CMD_NAME = "test1"; + + protected void run() throws OnapCommandException { + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientTest.java b/framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientTest.java new file mode 100644 index 00000000..720737b3 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientTest.java @@ -0,0 +1,201 @@ +/* + * 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.ad; + +import static org.junit.Assert.assertEquals; + +import mockit.Invocation; +import mockit.Mock; +import mockit.MockUp; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.onap.cli.fw.conf.OnapCommandConfg; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.error.OnapCommandHttpFailure; +import org.onap.cli.fw.error.OnapCommandServiceNotFound; +import org.onap.cli.fw.http.HttpInput; +import org.onap.cli.fw.http.HttpResult; +import org.onap.cli.fw.http.OnapHttpConnection; + +public class OnapAuthClientTest { + + OnapAuthClient client; + + @Before + public void setUp() throws OnapCommandHttpFailure { + OnapCredentials creds = new OnapCredentials("test", "test123", "http://192.168.99.10:80"); + client = new OnapAuthClient(creds, true); + } + + @Test + public void loginFailedAuthIgnoredTest() throws OnapCommandException { + OnapCredentials creds = new OnapCredentials("test", "test123", "http://192.168.99.10:80"); + OnapAuthClient client = new OnapAuthClient(creds, true); + if (OnapCommandConfg.isAuthIgnored()) { + client.getDebugInfo(); + client.login(); + assertEquals(null, client.getAuthToken()); + } + } + + @Test + public void logoutFailedAuthIgnoredTest() throws OnapCommandException { + OnapCredentials creds = new OnapCredentials("test", "test123", "http://192.168.99.10:80"); + OnapAuthClient client = new OnapAuthClient(creds, true); + if (OnapCommandConfg.isAuthIgnored()) { + client.logout(); + assertEquals(null, client.getAuthToken()); + } + } + + @Test + public void getMsbUrlTest() throws OnapCommandException { + OnapCredentials creds = new OnapCredentials("test", "test123", "http://192.168.99.10:80"); + OnapAuthClient client = new OnapAuthClient(creds, true); + OnapService srv = new OnapService(); + srv.setName("msb"); + String msb = client.getServiceBasePath(srv); + assertEquals("http://192.168.99.10:80/api/microservices/v1", msb); + } + + @Test(expected = OnapCommandServiceNotFound.class) + public void loginFailedServiceNotFoundTest() throws OnapCommandException { + mockIsAuthIgnored(false); + HttpResult result = new HttpResult(); + result.setStatus(404); + mockHttpRequest(result); + client.login(); + + } + + @Test(expected = OnapCommandExecutionFailed.class) + public void loginFailedCommandExecutionFailedTest() throws OnapCommandException { + + mockIsAuthIgnored(false); + HttpResult result = new HttpResult(); + result.setStatus(401); + mockHttpRequest(result); + client.login(); + } + + @Test(expected = OnapCommandExecutionFailed.class) + public void loginFailedWrongJasonBodyTest() throws OnapCommandException { + mockIsAuthIgnored(false); + HttpResult result = new HttpResult(); + result.setStatus(200); + mockHttpRequest(result); + client.login(); + } + + @Test + public void loginSuccessTest() { + + mockIsAuthIgnored(false); + HttpResult result = new HttpResult(); + result.setBody("{\"url\":\"http://192.168.4.47\"}"); + result.setStatus(200); + mockHttpConsecutiveRequest(result); + try { + client.login(); + } catch (OnapCommandException e) { + } + mockHttpRequest(null); + } + + @Test + public void logoutFailedTest() { + + mockIsAuthIgnored(false); + HttpResult result = new HttpResult(); + result.setBody("{\"url\":\"http://192.168.4.47\"}"); + result.setStatus(200); + mockHttpConsecutiveRequest(result); + try { + client.logout(); + } catch (OnapCommandException e) { + } + mockHttpRequest(null); + } + + @Test + public void logoutSuccessTest() { + + mockIsAuthIgnored(false); + HttpResult result = new HttpResult(); + result.setBody("{\"url\":\"http://192.168.4.47\"}"); + result.setStatus(204); + mockHttpConsecutiveRequest(result); + try { + client.logout(); + } catch (OnapCommandException e) { + } + mockHttpRequest(null); + } + + private void mockIsAuthIgnored(boolean isAuthIgnored) { + + new MockUp<OnapCommandConfg>() { + boolean isMock = true; + + @Mock + public boolean isAuthIgnored(Invocation inv) { + if (isMock) { + isMock = false; + return isAuthIgnored; + } else { + return inv.proceed(); + } + } + }; + } + + private static void mockHttpRequest(HttpResult result) { + new MockUp<OnapHttpConnection>() { + boolean isMock = true; + + @Mock + public HttpResult request(Invocation inv, HttpInput input) throws OnapCommandHttpFailure { + if (isMock) { + isMock = false; + return result; + } else { + return inv.proceed(input); + } + } + }; + } + + private void mockHttpConsecutiveRequest(HttpResult result) { + new MockUp<OnapHttpConnection>() { + @Mock + public HttpResult request(Invocation inv, HttpInput input) throws OnapCommandHttpFailure { + return result; + } + }; + } + + @AfterClass + public static void clear() { + HttpResult result = new HttpResult(); + result.setBody("{\"url\":\"http://192.168.4.47\"}"); + result.setStatus(200); + mockHttpRequest(result); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/ad/OnapCredentialsTest.java b/framework/src/test/java/org/onap/cli/fw/ad/OnapCredentialsTest.java new file mode 100644 index 00000000..a1987c08 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/ad/OnapCredentialsTest.java @@ -0,0 +1,32 @@ +/* + * 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.ad; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class OnapCredentialsTest { + + @Test + public void credentialsTest() { + OnapCredentials cre = new OnapCredentials("test", "test123", "url"); + assertTrue(cre.getUsername().equals("test") && cre.getPassword().equals("test123") + && cre.getMsbUrl().equals("url")); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java b/framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java new file mode 100644 index 00000000..f0ec8c63 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java @@ -0,0 +1,37 @@ +/* + * 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.ad; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class OnapServiceTest { + + @Test + public void serviceTest() { + OnapService ser = new OnapService(); + ser.setName("name"); + ser.setVersion("1.0"); + ser.setBasePath("basePath"); + ser.setNoAuth(true); + assertTrue(ser.getName().equals("name") && ser.getVersion().equals("1.0") + && ser.getBasePath().equals("basePath") && ser.isNoAuth()); + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapCreateSwaggerBasedCommand.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapCreateSwaggerBasedCommand.java new file mode 100644 index 00000000..069ae35f --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapCreateSwaggerBasedCommand.java @@ -0,0 +1,101 @@ +/* + * 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.cmd; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.error.OnapCommandExecutorInfoMissing; +import org.onap.cli.fw.error.OnapCommandInvalidParameterValue; +import org.onap.cli.fw.error.OnapCommandResultInitialzationFailed; +import org.onap.cli.fw.utils.OnapCommandUtils; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + +public class OnapCreateSwaggerBasedCommand extends OnapSwaggerCommand { + + private <T> T initializeEntity(T obj, List<String> prps) throws OnapCommandResultInitialzationFailed { + for (int i = 1; i < prps.size(); i++) { + String paramName = prps.get(i).trim(); + String prpName = paramName; + // paramName(prpName) + if (prpName.contains("(")) { + paramName = prpName.substring(0, prpName.indexOf("(")); + prpName = prpName.substring(prpName.indexOf("(") + 1, prpName.indexOf(")")); + } + String methodName = OnapCommandUtils.formMethodNameFromAttributeName(prpName, "set"); + + try { + Method set = obj.getClass().getMethod(methodName, String.class); + set.invoke(obj, this.getParametersMap().get(paramName).getValue()); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | OnapCommandInvalidParameterValue e) { + throw new OnapCommandResultInitialzationFailed(this.getName(), e); + } + } + return obj; + } + + @Override + protected void run() throws OnapCommandException { + if (this.getExecutor() == null) { + throw new OnapCommandExecutorInfoMissing(this.getName()); + } + + try { + // Initialize client + Class clientClaz = Class.forName(this.getExecutor().getClient()); + Object client = clientClaz.getConstructor().newInstance(); + this.initializeApiClient(client); + + // Initialize api + Class apiCls = Class.forName(this.getExecutor().getApi()); + Object api = apiCls.getConstructor(clientClaz).newInstance(client); + + // invoke method + List<String> methodTokens = Arrays.asList(this.getExecutor().getMethod().split(",")); + + List<String> entityTokens = Arrays.asList(this.getExecutor().getEntity().split(",")); + Class entityCls = Class.forName(entityTokens.get(0)); + Object entity = entityCls.newInstance(); + Method method = api.getClass().getMethod(methodTokens.get(0), entityCls); + Object result = method.invoke(api, this.initializeEntity(entity, entityTokens)); + + // initialize result + this.initializeResult(result); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + throw new OnapCommandExecutionFailed(this.getName(), e); + } catch (OnapCommandException e) { + throw e; + } catch (Exception e) { + try { + Class execCls = Class.forName(this.getExecutor().getException()); + Method execMethod = execCls.getClass().getMethod("getCode"); + if (execCls.isInstance(e)) { + throw new OnapCommandExecutionFailed(this.getName(), e, (Integer) execMethod.invoke(e)); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | ClassNotFoundException | NoSuchMethodException | SecurityException e1) { + throw new OnapCommandExecutionFailed(this.getName(), e1.getMessage()); + } + throw new OnapCommandExecutionFailed(this.getName(), e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapCreateSwaggerBasedCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapCreateSwaggerBasedCommandTest.java new file mode 100644 index 00000000..ec4b91d4 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapCreateSwaggerBasedCommandTest.java @@ -0,0 +1,32 @@ +/* + * 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.cmd; + +import org.junit.Test; +import org.onap.cli.fw.OnapCommand; +import org.onap.cli.fw.error.OnapCommandException; + +public class OnapCreateSwaggerBasedCommandTest { + + @Test + public void runTest() throws OnapCommandException { + OnapCommand cmd = new OnapCreateSwaggerBasedCommand(); + cmd.initializeSchema("sample-test-schema-swagger.yaml"); + //cmd.execute(); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapDeleteSwaggerBasedCommand.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapDeleteSwaggerBasedCommand.java new file mode 100644 index 00000000..1db954c6 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapDeleteSwaggerBasedCommand.java @@ -0,0 +1,75 @@ +/* + * 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.cmd; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.error.OnapCommandExecutorInfoMissing; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + +/** + * Helps to make delete rest calls on top of swagger generated java client. For example following one shows how MSB + * service list is achieved here exec: ... method: deleteMicroService, [input param name given under Parameters] + * + */ +public class OnapDeleteSwaggerBasedCommand extends OnapSwaggerCommand { + + @Override + protected void run() throws OnapCommandException { + if (this.getExecutor() == null) { + throw new OnapCommandExecutorInfoMissing(this.getName()); + } + + try { + // Initialize client + Class clientCls = Class.forName(this.getExecutor().getClient()); + Object client = clientCls.getConstructor().newInstance(); + this.initializeApiClient(client); + + // Initialize api + Class apiCls = Class.forName(this.getExecutor().getApi()); + Object api = apiCls.getConstructor(clientCls).newInstance(client); + + // invoke method + List<String> methodTokens = Arrays.asList(this.getExecutor().getMethod().split(",")); + + Method method = api.getClass().getMethod(methodTokens.get(0), String.class); + method.invoke(api, this.getParametersMap().get(methodTokens.get(1)).getValue()); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + throw new OnapCommandExecutionFailed(this.getName(), e); + } catch (OnapCommandException e) { + throw e; + } catch (Exception e) { + try { + Class execCls = Class.forName(this.getExecutor().getException()); + Method execMethod = execCls.getClass().getMethod("getCode"); + if (execCls.isInstance(e)) { + throw new OnapCommandExecutionFailed(this.getName(), e, (Integer) execMethod.invoke(e)); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | ClassNotFoundException | NoSuchMethodException | SecurityException e1) { + throw new OnapCommandExecutionFailed(this.getName(), e1.getMessage()); + } + throw new OnapCommandExecutionFailed(this.getName(), e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapDeleteSwaggerBasedCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapDeleteSwaggerBasedCommandTest.java new file mode 100644 index 00000000..a242a683 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapDeleteSwaggerBasedCommandTest.java @@ -0,0 +1,21 @@ +/* + * 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.cmd; + +public class OnapDeleteSwaggerBasedCommandTest { + +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapGetSwaggerBasedCommand.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapGetSwaggerBasedCommand.java new file mode 100644 index 00000000..8ed86564 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapGetSwaggerBasedCommand.java @@ -0,0 +1,79 @@ +/* + * 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.cmd; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.error.OnapCommandExecutorInfoMissing; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + +/** + * Helps to make get rest calls on top of swagger generated java client. For example following one shows how MSB service + * list is achieved here exec: ... method: getMicroService, [input param name given under Parameters] + * + */ +public class OnapGetSwaggerBasedCommand extends OnapSwaggerCommand { + + @Override + protected void run() throws OnapCommandException { + if (this.getExecutor() == null) { + throw new OnapCommandExecutorInfoMissing(this.getName()); + } + + try { + // Initialize client + Class clientCls = Class.forName(this.getExecutor().getClient()); + Object client = clientCls.getConstructor().newInstance(); + this.initializeApiClient(client); + + // Initialize api + Class apiCls = Class.forName(this.getExecutor().getApi()); + Object api = apiCls.getConstructor(clientCls).newInstance(client); + + // invoke method + List<String> methodTokens = Arrays.asList(this.getExecutor().getMethod().split(",")); + + Method method = api.getClass().getMethod(methodTokens.get(0), String.class); + Object result = method.invoke(api, this.getParametersMap().get(methodTokens.get(1)).getValue()); + + // initialize result + this.initializeResult(result); + + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + throw new OnapCommandExecutionFailed(this.getName(), e); + } catch (OnapCommandException e) { + throw e; + } catch (Exception e) { + try { + Class execCls = Class.forName(this.getExecutor().getException()); + Method execMethod = execCls.getClass().getMethod("getCode"); + if (execCls.isInstance(e)) { + throw new OnapCommandExecutionFailed(this.getName(), e, (Integer) execMethod.invoke(e)); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | ClassNotFoundException | NoSuchMethodException | SecurityException e1) { + throw new OnapCommandExecutionFailed(this.getName(), e1.getMessage()); + } + throw new OnapCommandExecutionFailed(this.getName(), e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapGetSwaggerBasedCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapGetSwaggerBasedCommandTest.java new file mode 100644 index 00000000..5c301a62 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapGetSwaggerBasedCommandTest.java @@ -0,0 +1,21 @@ +/* + * 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.cmd; + +public class OnapGetSwaggerBasedCommandTest { + +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java new file mode 100644 index 00000000..e7af1aa3 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java @@ -0,0 +1,79 @@ +/* + * 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.cmd; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.http.HttpInput; +import org.onap.cli.fw.input.OnapCommandParameter; +import org.onap.cli.fw.input.ParameterType; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class OnapHttpCommandTest { + + @Test(expected = OnapCommandException.class) + public void runTest() throws OnapCommandException { + OnapCommandParameter param1 = new OnapCommandParameter(); + param1.setLongOption("onap-username"); + param1.setName("onap-username"); + param1.setParameterType(ParameterType.STRING); + OnapCommandParameter param2 = new OnapCommandParameter(); + param2.setLongOption("onap-password"); + param2.setName("onap-password"); + param2.setParameterType(ParameterType.STRING); + OnapCommandParameter param3 = new OnapCommandParameter(); + param3.setLongOption("msb-url"); + param3.setName("msb-url"); + param3.setParameterType(ParameterType.STRING); + OnapCommandParameter param4 = new OnapCommandParameter(); + param4.setLongOption("string-param"); + param4.setName("string-param"); + param4.setParameterType(ParameterType.STRING); + OnapCommandParameter param5 = new OnapCommandParameter(); + param5.setLongOption("long-opt"); + param5.setName("long-opt"); + param5.setParameterType(ParameterType.STRING); + + List<OnapCommandParameter> paramslist = new ArrayList<>(); + paramslist.add(param1); + paramslist.add(param2); + paramslist.add(param3); + paramslist.add(param4); + paramslist.add(param5); + + HttpInput inp = new HttpInput(); + inp.setBody("body"); + inp.setMethod("method"); + inp.setReqCookies(new HashMap<String, String>()); + inp.setReqHeaders(new HashMap<String, String>()); + inp.setReqQueries(new HashMap<String, String>()); + inp.setUri("uri"); + + OnapHttpCommand com = new OnapHttpCommand(); + com.setParameters(paramslist); + com.getParameters(); + com.getParametersMap(); + com.setInput(inp); + com.initializeSchema("sample-test-schema.yaml"); + com.execute(); + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapListSwaggerBasedCommand.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapListSwaggerBasedCommand.java new file mode 100644 index 00000000..a5795e75 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapListSwaggerBasedCommand.java @@ -0,0 +1,78 @@ +/* + * 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.cmd; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.error.OnapCommandExecutorInfoMissing; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Helps to make list rest calls on top of swagger generated java client. For example following one shows how MSB + * service list is achived here exec: api: + * org.onap.common_services.microservice_bus.apiroute_service.client.api.MSBServiceResourceApi client: + * org.onap.common_services.microservice_bus.apiroute_service.client.invoker.ApiClient method: getMicroService + * exception: org.onap.common_services.microservice_bus.apiroute_service.client.invoker.ApiException + * + */ +public class OnapListSwaggerBasedCommand extends OnapSwaggerCommand { + + @Override + protected void run() throws OnapCommandException { + if (this.getExecutor() == null) { + throw new OnapCommandExecutorInfoMissing(this.getName()); + } + + try { + // Initialize client + Class clientCls = Class.forName(this.getExecutor().getClient()); + Object client = clientCls.getConstructor().newInstance(); + this.initializeApiClient(client); + + // Initialize api + Class apiCls = Class.forName(this.getExecutor().getApi()); + Object api = apiCls.getConstructor(clientCls).newInstance(client); + + // invoke method + Method method = api.getClass().getMethod(this.getExecutor().getMethod()); + Object result = method.invoke(api); + + // initialize result + this.initializeResult(result); + + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + throw new OnapCommandExecutionFailed(this.getName(), e); + } catch (OnapCommandException e) { + throw e; + } catch (Exception e) { + try { + Class execCls = Class.forName(this.getExecutor().getException()); + Method execMethod = execCls.getClass().getMethod("getCode"); + if (execCls.isInstance(e)) { + throw new OnapCommandExecutionFailed(this.getName(), e, (Integer) execMethod.invoke(e)); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | ClassNotFoundException | NoSuchMethodException | SecurityException e1) { + throw new OnapCommandExecutionFailed(this.getName(), e1.getMessage()); + } + throw new OnapCommandExecutionFailed(this.getName(), e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapListSwaggerBasedCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapListSwaggerBasedCommandTest.java new file mode 100644 index 00000000..5683153c --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapListSwaggerBasedCommandTest.java @@ -0,0 +1,21 @@ +/* + * 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.cmd; + +public class OnapListSwaggerBasedCommandTest { + +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommandTest.java new file mode 100644 index 00000000..1c09c0d3 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommandTest.java @@ -0,0 +1,56 @@ +/* + * 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.cmd; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.input.OnapCommandParameter; + +public class OnapSchemaRefreshCommandTest { + + @Test + public void validateSchemaCommandTest1() throws OnapCommandException { + OnapSchemaRefreshCommand cmd = new OnapSchemaRefreshCommand(); + cmd.initializeSchema("schema-refresh.yaml"); + for (OnapCommandParameter param : cmd.getParameters()) { + if ("onap-username".equals(param.getName())) { + param.setValue("test"); + } else if ("onap-password".equals(param.getName())) { + param.setValue("test"); + } else if ("msb-url".equals(param.getName())) { + param.setValue("test-url"); + } + } + cmd.execute(); + } + + @Test + public void validateSchemaCommandTest2() throws OnapCommandException { + OnapSchemaRefreshCommand cmd = new OnapSchemaRefreshCommand(); + cmd.initializeSchema("schema-refresh.yaml"); + for (OnapCommandParameter param : cmd.getParameters()) { + if ("onap-username".equals(param.getName())) { + param.setValue("test"); + } else if ("onap-password".equals(param.getName())) { + param.setValue("test"); + } else if ("msb-url".equals(param.getName())) { + param.setValue("test-url"); + } + } + cmd.execute(); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java new file mode 100644 index 00000000..b70bf6f9 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java @@ -0,0 +1,64 @@ +/* + * 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.cmd; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.input.OnapCommandParameter; +import org.onap.cli.fw.schema.ValidateSchemaTest; + +public class OnapSchemaValidateCommandTest { + + @Test + public void validateSchemaCommandTest1() throws OnapCommandException { + OnapSchemaValidateCommand cmd = new OnapSchemaValidateCommand(); + cmd.initializeSchema("schema-validate.yaml"); + for (OnapCommandParameter param : cmd.getParameters()) { + if ("onap-username".equals(param.getName())) { + param.setValue("test"); + } else if ("onap-password".equals(param.getName())) { + param.setValue("test"); + } else if ("msb-url".equals(param.getName())) { + param.setValue("test-url"); + } else if ("schema-location".equals(param.getName())) { + param.setValue("schema-validate-pass.yaml"); + } else if ("internal-schema".equals(param.getName())) { + param.setValue("true"); + } + } + cmd.execute(); + } + + @Test + public void validateSchemaCommandTest2() throws OnapCommandException { + OnapSchemaValidateCommand cmd = new OnapSchemaValidateCommand(); + cmd.initializeSchema("schema-validate.yaml"); + for (OnapCommandParameter param : cmd.getParameters()) { + if ("onap-username".equals(param.getName())) { + param.setValue("test"); + } else if ("onap-password".equals(param.getName())) { + param.setValue("test"); + } else if ("msb-url".equals(param.getName())) { + param.setValue("test-url"); + } else if ("schema-location".equals(param.getName())) { + param.setValue( + ValidateSchemaTest.class.getClassLoader().getResource("schema-validate-pass.yaml").getFile()); + } + } + cmd.execute(); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapSwaggerCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSwaggerCommandTest.java new file mode 100644 index 00000000..628b9a42 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSwaggerCommandTest.java @@ -0,0 +1,96 @@ +/* + * 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.cmd; + +import org.junit.Test; +import org.onap.cli.fw.OnapCommand; +import org.onap.cli.fw.error.OnapCommandClientInitialzationFailed; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandResultInitialzationFailed; +import org.onap.cli.fw.input.OnapCommandParameter; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class OnapSwaggerCommandTest { + + @Test(expected = OnapCommandResultInitialzationFailed.class) + public void initializeResultTest1() throws OnapCommandException { + OnapSwaggerCommandImpl swagger = new OnapSwaggerCommandImpl(); + swagger.initializeSchema("onap-test-schema.yaml"); + List<String> obj = new ArrayList<>(); + obj.add("name"); + obj.add("get"); + swagger.initializeResult(obj); + + Set<String> obj1 = new HashSet<>(); + obj.add("name"); + obj.add("get"); + swagger.initializeResult(obj1); + } + + @Test(expected = OnapCommandResultInitialzationFailed.class) + public void initializeResultTest2() throws OnapCommandException { + OnapSwaggerCommandImpl swagger = new OnapSwaggerCommandImpl(); + swagger.initializeSchema("onap-test-schema.yaml"); + Set<String> obj1 = new HashSet<>(); + obj1.add("name"); + obj1.add("get"); + swagger.initializeResult(obj1); + } + + @Test(expected = NullPointerException.class) + public void initializeResultTest3() throws OnapCommandException { + OnapSwaggerCommandImpl swagger = new OnapSwaggerCommandImpl(); + swagger.initializeSchema("onap-test-schema.yaml"); + ApiClient cit = new ApiClient(); + cit.setApiKey("apiKey"); + cit.setBasePath("basePath"); + swagger.initializeApiClient(cit); + } + + class OnapSwaggerCommandImpl extends OnapSwaggerCommand { + protected void run() throws OnapCommandException { + } + + } + + class ApiClient { + + private String basePath; + private String apiKey; + + public String getBasePath() { + return basePath; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java b/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java new file mode 100644 index 00000000..e345945b --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java @@ -0,0 +1,44 @@ +/* + * 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.conf; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.Properties; + +public class OnapCommandConfgTest { + + @Test + public void versionTest() { + String str = OnapCommandConfg.getVersion(); + Assert.assertTrue(str != null); + } + + @Test + public void isAuthIgnoredTest() throws IOException { + Properties prps = new Properties(); + prps.load(OnapCommandConfg.class.getClassLoader().getResourceAsStream("onap.properties")); + boolean auth = OnapCommandConfg.isAuthIgnored(); + Assert.assertTrue(auth == Boolean.valueOf(prps.getProperty("cli.ignore_auth"))); + Assert.assertTrue(OnapCommandConfg.isCookiesBasedAuth() == Boolean + .valueOf(prps.getProperty("http.api_key_use_cookies"))); + Assert.assertTrue("X-Auth-Token".equals(OnapCommandConfg.getXAuthTokenName())); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java b/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java new file mode 100644 index 00000000..1d0c1a6b --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java @@ -0,0 +1,270 @@ +/* + * 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.error; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class OnapCommandErrorTest { + + @Test + public void onapCommandDiscoveryFailedTest() { + OnapCommandDiscoveryFailed failed = new OnapCommandDiscoveryFailed("name"); + assertEquals("0x0010::Failed auto discover schema files from name under class path, ", failed.getMessage()); + failed = new OnapCommandDiscoveryFailed("directory", "name"); + assertEquals("0x0010::Failed auto generate json file 'name' under class path directory 'directory' , ", + failed.getMessage()); + } + + @Test + public void onapCommandInvalidParameterValueTest() { + OnapCommandInvalidParameterValue failed = new OnapCommandInvalidParameterValue("name"); + assertEquals("0x0028::Parameter name value is invalid, ", failed.getMessage()); + } + + @Test + public void onapCommandResultMapProcessingFailedTest() { + OnapCommandResultMapProcessingFailed failed = new OnapCommandResultMapProcessingFailed("name", + new Exception("")); + assertEquals("0x0028::Failed to process the result map name in http section, ", failed.getMessage()); + } + + @Test + public void onapCommandHttpHeaderNotFoundTest() { + OnapCommandHttpHeaderNotFound failed = new OnapCommandHttpHeaderNotFound("name"); + assertEquals("0x0027::Http header name is not returned from the service", failed.getMessage()); + } + + @Test + public void onapCommandClientInitialzationFailedTest() { + OnapCommandClientInitialzationFailed failed = new OnapCommandClientInitialzationFailed("Test", + new Exception("Test Command Failed")); + assertEquals("0x0021::API client for the command Test is failed, Test Command Failed", failed.getMessage()); + } + + @Test + public void onapCommandExceptionTest1() { + OnapCommandException failed = new OnapCommandException("1", "Test Command Failed"); + assertEquals("1::Test Command Failed", failed.getMessage()); + } + + @Test + public void onapCommandExceptionTest2() { + OnapCommandException failed = new OnapCommandException("1", "Test Command Failed", 201); + assertEquals("201::1::Test Command Failed", failed.getMessage()); + } + + @Test + public void onapCommandExecutionFailedTest1() { + OnapCommandExecutionFailed failed = new OnapCommandExecutionFailed("Test", "Test Command Failed", 201); + assertEquals("201::0x0001::Command Test failed to execute, Test Command Failed", failed.getMessage()); + failed = new OnapCommandExecutionFailed("Test", new Exception("Test Command Failed"), 201); + assertEquals("201::0x0001::Command Test failed to execute, Test Command Failed", failed.getMessage()); + } + + @Test + public void onapCommandExecutionFailedTest2() { + OnapCommandExecutionFailed failed = new OnapCommandExecutionFailed("Test Command Failed"); + assertEquals("0x0001::Test Command Failed", failed.getMessage()); + } + + @Test + public void onapCommandExecutionFailedTest3() { + OnapCommandExecutionFailed failed = new OnapCommandExecutionFailed("Test", "Test Command Failed"); + assertEquals("0x0001::Command Test failed to execute, Test Command Failed", failed.getMessage()); + + failed = new OnapCommandExecutionFailed("Test", new Exception("Test Command Failed")); + assertEquals("0x0001::Command Test failed to execute, Test Command Failed", failed.getMessage()); + } + + @Test + public void onapCommandExecutorInfoMissingTest() { + OnapCommandExecutorInfoMissing failed = new OnapCommandExecutorInfoMissing("Test"); + + assertEquals("0x0023::Command Test excutor info is missing from schema", failed.getMessage()); + } + + @Test + public void onapCommandHelpFailedTest() { + OnapCommandHelpFailed failed = new OnapCommandHelpFailed(new Exception("Failed")); + + assertEquals("0x0002::Command failed to print help message, Failed", failed.getMessage()); + } + + @Test + public void onapCommandHttpFailureTest1() { + OnapCommandHttpFailure failed = new OnapCommandHttpFailure("Failed"); + assertEquals("0x0025::Failed", failed.getMessage()); + + failed = new OnapCommandHttpFailure(new Exception("failed"), 201); + assertEquals("201::0x0025::failed", failed.getMessage()); + } + + @Test + public void onapCommandHttpFailureTest2() { + OnapCommandHttpFailure failed = new OnapCommandHttpFailure("Failed", 203); + + assertEquals("203::0x0025::Failed", failed.getMessage()); + } + + @Test + public void onapCommandInvalidParameterTypeTest() { + OnapCommandInvalidParameterType failed = new OnapCommandInvalidParameterType("Failed"); + + assertEquals("0x0003::Parameter type Failed is invalid", failed.getMessage()); + } + + @Test + public void onapCommandInvalidPrintDirectionTest() { + OnapCommandInvalidPrintDirection failed = new OnapCommandInvalidPrintDirection("Direction"); + + assertEquals("0x0004::Print direction Direction is invalid", failed.getMessage()); + } + + @Test + public void onapCommandInvalidRegistrationTest() { + OnapCommandInvalidRegistration failed = new OnapCommandInvalidRegistration(OnapCommandErrorTest.class); + + assertEquals("0x0005::Invalid commad class org.onap.cli.fw.error.OnapCommandErrorTest registration, " + + "it should be derived from org.onap.cli.fw.OnapCommand", failed.getMessage()); + } + + @Test + public void onapCommandInvalidResultAttributeScopeTest() { + OnapCommandInvalidResultAttributeScope failed = new OnapCommandInvalidResultAttributeScope("Attribute"); + + assertEquals("0x0006::Result atrribute Attribute is invalid", failed.getMessage()); + } + + @Test + public void onapCommandInvalidSchemaTest() { + OnapCommandInvalidSchema failed = new OnapCommandInvalidSchema("Schema", "Failed"); + + assertEquals("0x0007::Command schema Schema is invalid, Failed", failed.getMessage()); + } + + @Test + public void onapCommandInvalidSchemaVersionTest() { + OnapCommandInvalidSchemaVersion failed = new OnapCommandInvalidSchemaVersion("1.0"); + + assertEquals("0x0008::Command schema onap_cmd_schema_version 1.0 is invalid or missing", failed.getMessage()); + } + + @Test + public void onapCommandLoginFailedTest1() { + OnapCommandLoginFailed failed = new OnapCommandLoginFailed(new Exception("Failed")); + + assertEquals("0x0009::Login failed, Failed", failed.getMessage()); + } + + @Test + public void onapCommandLoginFailedTest2() { + OnapCommandLoginFailed failed = new OnapCommandLoginFailed("Failed", 201); + + assertEquals("201::0x0009::Login failed, Failed", failed.getMessage()); + } + + @Test + public void onapCommandLogoutFailedTest() { + OnapCommandLogoutFailed failed = new OnapCommandLogoutFailed(new Exception("Failed")); + assertEquals("0x0010::Logout failed, Failed", failed.getMessage()); + + failed = new OnapCommandLogoutFailed(200); + assertEquals("200::0x0010::Logout failed, ", failed.getMessage()); + } + + @Test + public void onapCommandNotFoundTest() { + OnapCommandNotFound failed = new OnapCommandNotFound("Test"); + + assertEquals("0x0011::Command Test is not registered", failed.getMessage()); + } + + @Test + public void onapCommandNotInitializedTest() { + OnapCommandNotInitialized failed = new OnapCommandNotInitialized("Test"); + + assertEquals("0x0012::Command Test is not initialized", failed.getMessage()); + } + + @Test + public void onapCommandOutputPrintingFailedTest() { + OnapCommandOutputPrintingFailed failed = new OnapCommandOutputPrintingFailed(new Exception("error")); + + assertEquals("0x0014::Command is failed to print the result, error", failed.getMessage()); + } + + @Test + public void onapCommandParameterMissingTest() { + OnapCommandParameterMissing failed = new OnapCommandParameterMissing("paramName"); + + assertEquals("0x0015::Parameter paramName is mandatory", failed.getMessage()); + } + + @Test + public void onapCommandParameterNameConflictTest() { + OnapCommandParameterNameConflict failed = new OnapCommandParameterNameConflict("paramName"); + + assertEquals("0x0016::Parameter name paramName is in conflict", failed.getMessage()); + } + + @Test + public void onapCommandParameterOptionConflictTest() { + OnapCommandParameterOptionConflict failed = new OnapCommandParameterOptionConflict("option"); + + assertEquals("0x0017::Parameter option option is in conflict, only one option is allowed with given name", + failed.getMessage()); + } + + @Test + public void onapCommandRegistrationFailedTest() { + OnapCommandRegistrationFailed failed = new OnapCommandRegistrationFailed("Test", "error"); + + assertEquals("0x0018::Command Test is failed to register, error", failed.getMessage()); + } + + @Test + public void onapCommandResultInitialzationFailedTest() { + OnapCommandResultInitialzationFailed failed = new OnapCommandResultInitialzationFailed("Test", + new Exception("error")); + + assertEquals("0x0022::Command Test result format is failed, error", failed.getMessage()); + } + + @Test + public void onapCommandSchemaNotFoundTest() { + OnapCommandSchemaNotFound failed = new OnapCommandSchemaNotFound("Test"); + + assertEquals("0x0019::Command schema Test is not found, ", failed.getMessage()); + } + + @Test + public void onapCommandServiceNotFoundTest() { + OnapCommandServiceNotFound failed = new OnapCommandServiceNotFound("Service"); + + assertEquals("0x0020::Service Service is not found in MSB", failed.getMessage()); + } + + @Test + public void onapCommandOutputFormatNotsupportedTest() { + OnapCommandOutputFormatNotsupported failed = new OnapCommandOutputFormatNotsupported("Format"); + + assertEquals("0x0013::Command does not support the output format Format", failed.getMessage()); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java b/framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java new file mode 100644 index 00000000..900d72e8 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2016-17 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; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.util.HashMap; + +public class HttpInputOutputTest { + + @Test + public void httpInputTest() { + HttpInput inp = new HttpInput(); + inp.setBody("body"); + inp.setMethod("method"); + inp.setReqCookies(null); + inp.setReqHeaders(null); + inp.setReqQueries(null); + inp.setUri("uri"); + + assertTrue("body".equals(inp.getBody()) && "method".equals(inp.getMethod()) && null == inp.getReqCookies() + && inp.getReqHeaders().isEmpty() && inp.getReqQueries().isEmpty() && "uri".equals(inp.getUri())); + + inp.setReqCookies(new HashMap<String, String>()); + inp.setReqHeaders(new HashMap<String, String>()); + inp.setReqQueries(new HashMap<String, String>()); + + assertTrue( + "\nURL: uri\nMethod: method\nRequest Queries: {}\nRequest Body: body\nRequest Headers: {}\nRequest Cookies: {}\nbinaryData=false" + .equals(inp.toString())); + } + + @Test + public void httpResultTest() { + HttpResult out = new HttpResult(); + out.setBody("body"); + out.setRespCookies(null); + out.setRespHeaders(null); + out.setStatus(205); + + assertTrue("body".equals(out.getBody()) && null == out.getRespCookies() && null == out.getRespHeaders() + && 205 == out.getStatus()); + + out.setRespCookies(new HashMap<String, String>()); + out.setRespHeaders(new HashMap<String, String>()); + out.setStatus(200); + assertTrue("\nHTTP Status: 200\nResponse Body: body\nResponse Headers: {}\nResponse Cookies: {}" + .equals(out.toString())); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java b/framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java new file mode 100644 index 00000000..cf6d73c1 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java @@ -0,0 +1,207 @@ +/* + * 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; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import mockit.Invocation; +import mockit.Mock; +import mockit.MockUp; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.protocol.HttpContext; +import org.junit.Before; +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandHttpFailure; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class OnapHttpConnectionTest { + HttpInput inp = null; + OnapHttpConnection con = null; + + @Before + public void setup() { + mockHttpRequest(null); + inp = new HttpInput(); + inp.setMethod("get"); + inp.setBody("body"); + Map<String, String> map1 = new HashMap<>(); + map1.put("header1", "value1"); + inp.setReqHeaders(map1); + Map<String, String> map2 = new HashMap<>(); + map2.put("query1", "value1"); + inp.setReqQueries(map2); + Map<String, String> map = new HashMap<>(); + map.put("cookie1", "value1"); + inp.setReqCookies(map); + inp.setUri("http://192.168.99.10:80"); + } + + @Test(expected = OnapCommandHttpFailure.class) + public void httpUnSecuredGetExceptionTest() throws OnapCommandHttpFailure { + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + inp.setMethod("get"); + con = new OnapHttpConnection(false, true); + con.getDebugInfo(); + con.setAuthToken("fdsfdsfs"); + assertTrue("fdsfdsfs".equals(con.getAuthToken())); + con.get(inp); + + } + + @Test(expected = OnapCommandHttpFailure.class) + public void httpUnSecuredPostExceptionTest() throws OnapCommandHttpFailure { + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + + inp.setMethod("post"); + con = new OnapHttpConnection(false, true); + con.post(inp); + } + + + @Test(expected = OnapCommandHttpFailure.class) + public void httpUnSecuredPostExceptionTest1() throws OnapCommandHttpFailure { + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + + inp.setMethod("post"); + inp.setBinaryData(true); + con = new OnapHttpConnection(false, true); + con.post(inp); + } + + @Test(expected = OnapCommandHttpFailure.class) + public void httpUnSecuredPutExceptionTest() throws OnapCommandHttpFailure { + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + inp.setMethod("put"); + con = new OnapHttpConnection(false, true); + con.put(inp); + } + + @Test(expected = OnapCommandHttpFailure.class) + public void httpUnSecuredDeleteExceptionTest() throws OnapCommandHttpFailure { + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + inp.setMethod("delete"); + con = new OnapHttpConnection(false, true); + con.delete(inp); + } + + @Test(expected = IllegalArgumentException.class) + public void httpUnSecuredOtherExceptionTest() throws OnapCommandHttpFailure { + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + inp.setMethod("other"); + con = new OnapHttpConnection(false, true); + con.request(inp); + } + + @Test() + public void httpUnSecuredCloseExceptionTest() throws OnapCommandHttpFailure { + inp.setMethod("other"); + con = new OnapHttpConnection(false, true); + con.close(); + } + + @Test + public void httpSecuredGetExceptionTest() { + + // ProtocolVersion p = new ProtocolVersion("http",1,0); + // HttpResponse hr = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(p, 200 , null) ; + + new MockUp<CloseableHttpClient>() { + @Mock + public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) + throws IOException, ClientProtocolException { + + throw new IOException("IO Exception"); + } + }; + try { + HttpInput inp = new HttpInput(); + inp.setMethod("get"); + inp.setBody("body"); + inp.setReqHeaders(new HashMap<String, String>()); + inp.setReqQueries(new HashMap<String, String>()); + inp.setUri("http://192.168.99.10:80"); + OnapHttpConnection con = new OnapHttpConnection(true, false); + con.get(inp); + } catch (OnapCommandHttpFailure e) { + assertEquals("0x0025::IO Exception", e.getMessage()); + } + } + + private static void mockHttpRequest(HttpResult result) { + new MockUp<OnapHttpConnection>() { + boolean isMock = false; + + @Mock + public HttpResult request(Invocation inv, HttpInput input) throws OnapCommandHttpFailure { + if (isMock) { + return result; + } else { + return inv.proceed(input); + } + } + }; + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java b/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java new file mode 100644 index 00000000..40b07861 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java @@ -0,0 +1,121 @@ +/* + * 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.input; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandInvalidParameterValue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class OnapCommandParameterTest { + + @Test + public void parameterObjTest() throws OnapCommandInvalidParameterValue { + OnapCommandParameter param = new OnapCommandParameter(); + param.setDefaultValue("defaultValue"); + param.setDescription("description"); + param.setLongOption("longOption"); + param.setName("name"); + param.setOptional(true); + param.setParameterType(ParameterType.JSON); + param.setSecured(false); + param.setShortOption("shortOption"); + param.setValue("value"); + + assertTrue(param.getDefaultValue().equals("defaultValue") && param.getDescription().equals("description") + && param.getLongOption().equals("longOption") && param.getName().equals("name") + && param.getShortOption().equals("shortOption") && param.getValue().equals("value") + && param.isOptional() && !param.isSecured() && param.getParameterType().equals(ParameterType.JSON)); + + assertTrue("value".equals(param.getValue())); + + param.setParameterType(ParameterType.ARRAY); + param.setValue(Arrays.asList("1", "2", "3")); + assertTrue("[\"1\",\"2\",\"3\"]".equals(param.getValue())); + + param.setParameterType(ParameterType.MAP); + Map<String, String> map = new HashMap<>(); + map.put("One", "1"); + map.put("Two", "2"); + map.put("Three", "3"); + param.setValue(map); + assertTrue("{\"One\":\"1\",\"Two\":\"2\",\"Three\":\"3\"}".equals(param.getValue())); + + param.setDefaultValue("${defaultValue}"); + assertTrue(null == param.getDefaultValue()); + } + + @Test + public void parameterEnvDefaultValueObjTest() { + OnapCommandParameter param = new OnapCommandParameter(); + param.setDefaultValue("${DAFAULT_VALUE}"); + boolean isDefaultValueAnEnv = param.isDefaultValueAnEnv(); + assertTrue(isDefaultValueAnEnv); + + String envValue = param.getEnvVarNameFromDefaultValue(); + + assertTrue("DAFAULT_VALUE".equals(envValue)); + } + + @Test + public void parameterValidateTest() { + OnapCommandParameter param = new OnapCommandParameter(); + param.setOptional(false); + param.setValue(""); + param.setDefaultValue(""); + param.setParameterType(ParameterType.STRING); + try { + param.validate(); + } catch (OnapCommandException e) { + assertTrue("0x0015::Parameter null is mandatory".equals(e.getMessage())); + } + } + + @Test(expected = OnapCommandInvalidParameterValue.class) + public void onapCommandInvalidParameterValueArrayExeceptionTest() throws OnapCommandInvalidParameterValue { + OnapCommandParameter param = new OnapCommandParameter(); + param.setName("name"); + param.setParameterType(ParameterType.ARRAY); + param.setValue("value"); + assertTrue("[\"1\",\"2\",\"3\"]".equals(param.getValue())); + + } + + @Test(expected = OnapCommandInvalidParameterValue.class) + public void onapCommandInvalidParameterValueMapExeceptionTest() throws OnapCommandInvalidParameterValue { + OnapCommandParameter param = new OnapCommandParameter(); + param.setName("name"); + param.setParameterType(ParameterType.MAP); + param.setValue("value"); + assertTrue("{\"One\":\"1\",\"Two\":\"2\",\"Three\":\"3\"}".equals(param.getValue())); + } + + @Test(expected = OnapCommandInvalidParameterValue.class) + public void onapCommandInvalidParameterValueBinaryExeceptionTest() throws OnapCommandException { + OnapCommandParameter param = new OnapCommandParameter(); + param.setName("name"); + param.setParameterType(ParameterType.BINARY); + param.setValue("value"); + param.validate(); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java b/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java new file mode 100644 index 00000000..eef49ad8 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java @@ -0,0 +1,51 @@ +/* + * 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.input; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandInvalidParameterType; + +public class ParameterTypeTest { + @Test + public void paramTypeGetTest() { + + try { + assertTrue(ParameterType.JSON.equals(ParameterType.get("json")) + && ParameterType.YAML.equals(ParameterType.get("yaml")) + && ParameterType.STRING.equals(ParameterType.get("string")) + && ParameterType.LONG.equals(ParameterType.get("long")) + && ParameterType.URL.equals(ParameterType.get("url")) + && ParameterType.BOOL.equals(ParameterType.get("bool")) + && ParameterType.MAP.equals(ParameterType.get("map")) + && ParameterType.BINARY.equals(ParameterType.get("binary")) + && ParameterType.ARRAY.equals(ParameterType.get("array"))); + } catch (OnapCommandInvalidParameterType e) { + fail("Shouldn't have thrown this exception : " + e.getMessage()); + } + + try { + ParameterType.get("name"); + } catch (OnapCommandInvalidParameterType e) { + assertTrue("0x0003::Parameter type name is invalid".equals(e.getMessage())); + } + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/log/OnapCommandLoggerTest.java b/framework/src/test/java/org/onap/cli/fw/log/OnapCommandLoggerTest.java new file mode 100644 index 00000000..4b675edc --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/log/OnapCommandLoggerTest.java @@ -0,0 +1,134 @@ +/* + * Copyright 2016-17 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.log; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.reflect.SourceLocation; +import org.aspectj.runtime.internal.AroundClosure; +import org.junit.Test; + +public class OnapCommandLoggerTest { + + @Test + public void logTest() throws Throwable { + + + ProceedingJoinPoint point = new ProceedingJoinPoint() { + @Override + public String toShortString() { + return null; + } + + @Override + public String toLongString() { + return null; + } + + @Override + public Object getThis() { + return new Object(); + } + + @Override + public Object getTarget() { + return null; + } + + @Override + public StaticPart getStaticPart() { + return null; + } + + @Override + public SourceLocation getSourceLocation() { + return null; + } + + @Override + public Signature getSignature() { + return new Signature(){ + + @Override + public Class getDeclaringType() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDeclaringTypeName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getModifiers() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String toLongString() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String toShortString() { + // TODO Auto-generated method stub + return null; + } + + }; + } + + @Override + public String getKind() { + return null; + } + + @Override + public Object[] getArgs() { + return null; + } + + @Override + public void set$AroundClosure(AroundClosure arg0) { + } + + @Override + public Object proceed(Object[] arg0) throws Throwable { + return null; + } + + @Override + public Object proceed() throws Throwable { + return new Object(); + } + }; + + OnapCommandLogger log = new OnapCommandLogger(); + log.log(point); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java new file mode 100644 index 00000000..ac1a6d33 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java @@ -0,0 +1,41 @@ +/* + * 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.output; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.cli.fw.input.ParameterType; + +import java.util.Collections; + +public class OnapCommandResultAttributeScopeTest { + @Test + public void onapCommandResultAttributeTest() { + OnapCommandResultAttribute att = new OnapCommandResultAttribute(); + att.setDescription("description"); + att.setName("name"); + att.setScope(OnapCommandResultAttributeScope.LONG); + att.setSecured(true); + att.setType(ParameterType.LONG); + att.setValues(Collections.emptyList()); + assertTrue("description".equals(att.getDescription()) && "name".equals(att.getName()) + && OnapCommandResultAttributeScope.LONG.equals(att.getScope()) + && ParameterType.LONG.equals(att.getType()) && att.getValues().isEmpty()); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeTest.java b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeTest.java new file mode 100644 index 00000000..6d2612f9 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeTest.java @@ -0,0 +1,44 @@ +/* + * 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.output; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandInvalidResultAttributeScope; + +public class OnapCommandResultAttributeTest { + @Test + public void paramTypeGetTest() { + + try { + assertTrue(OnapCommandResultAttributeScope.LONG.equals(OnapCommandResultAttributeScope.get("long")) + && OnapCommandResultAttributeScope.SHORT.equals(OnapCommandResultAttributeScope.get("short"))); + } catch (OnapCommandInvalidResultAttributeScope e) { + fail("Shouldn't have thrown this exception : " + e.getMessage()); + } + + try { + OnapCommandResultAttributeScope.get("name"); + } catch (OnapCommandInvalidResultAttributeScope e) { + assertTrue("0x0006::Result atrribute name is invalid".equals(e.getMessage())); + } + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java new file mode 100644 index 00000000..dddab1bc --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java @@ -0,0 +1,208 @@ +/* + * 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.output; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Ignore; +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.input.ParameterType; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class OnapCommandResultTest { + + @Test + public void commandResultObjTest() throws OnapCommandException { + OnapCommandResult res = new OnapCommandResult(); + res.setDebugInfo("debugInfo"); + res.setIncludeSeparator(true); + res.setIncludeTitle(true); + res.setOutput("Output"); + res.setPrintDirection(PrintDirection.LANDSCAPE); + res.setRecords(new ArrayList<OnapCommandResultAttribute>()); + res.setScope(OnapCommandResultAttributeScope.LONG); + res.setType(ResultType.TABLE); + res.setDebug(true); + + assertTrue("debugInfo".equals(res.getDebugInfo()) && res.isIncludeSeparator() + && "Output".equals(res.getOutput()) && PrintDirection.LANDSCAPE.equals(res.getPrintDirection()) + && res.getRecords().isEmpty() && OnapCommandResultAttributeScope.LONG.equals(res.getScope()) + && ResultType.TABLE.equals(res.getType())); + + String help = res.print(); + + assertTrue("".equals(help)); + + } + + @Test + public void commandResultPrintLandscapeTableTest() throws OnapCommandException { + OnapCommandResult res = new OnapCommandResult(); + res.setDebugInfo("debugInfo"); + res.setIncludeSeparator(true); + res.setIncludeTitle(true); + res.setOutput("Output"); + res.setPrintDirection(PrintDirection.LANDSCAPE); + + OnapCommandResultAttribute att = new OnapCommandResultAttribute(); + att.setName("param"); + att.setDescription("description"); + att.setType(ParameterType.STRING); + att.setValues(new ArrayList<String>(Arrays.asList(new String[] { "value" }))); + List<OnapCommandResultAttribute> list = new ArrayList<OnapCommandResultAttribute>(); + list.add(att); + res.setRecords(list); + res.setScope(OnapCommandResultAttributeScope.LONG); + res.setType(ResultType.TABLE); + res.getRecordsMap(); + String expRes = "+--------+\n|param |\n+--------+\n|value |\n+--------+\n"; + String result = res.print(); + + assertEquals(expRes, result); + + } + + @Test + public void commandResultPrintLandscapeJsonTest() throws OnapCommandException { + OnapCommandResult res = new OnapCommandResult(); + res.setDebugInfo("debugInfo"); + res.setIncludeSeparator(true); + res.setIncludeTitle(true); + res.setOutput("Output"); + res.setPrintDirection(PrintDirection.LANDSCAPE); + + OnapCommandResultAttribute att = new OnapCommandResultAttribute(); + att.setName("param"); + att.setDescription("description"); + att.setType(ParameterType.JSON); + att.setValues( + new ArrayList<String>(Arrays.asList(new String[] { "{\"id\": \"0001\",\"value\": \"result\"}" }))); + List<OnapCommandResultAttribute> list = new ArrayList<OnapCommandResultAttribute>(); + list.add(att); + res.setRecords(list); + res.setScope(OnapCommandResultAttributeScope.LONG); + res.setType(ResultType.JSON); + + // Will be handled after the json print is implemented + String result = res.print(); + // String expRes = "+--------+\n|param |\n+--------+\n|value + // |\n+--------+\n"; + // assertEquals(expRes,result); + + } + + @Test + @Ignore + public void commandResultPrintLandscapeCsvTest() throws OnapCommandException { + OnapCommandResult res = new OnapCommandResult(); + res.setDebugInfo("debugInfo"); + res.setIncludeSeparator(true); + res.setIncludeTitle(true); + res.setOutput("Output"); + res.setPrintDirection(PrintDirection.LANDSCAPE); + + OnapCommandResultAttribute att = new OnapCommandResultAttribute(); + att.setName("param"); + att.setDescription("description"); + att.setType(ParameterType.STRING); + att.setValues(new ArrayList<String>(Arrays.asList(new String[] { "value" }))); + List<OnapCommandResultAttribute> list = new ArrayList<OnapCommandResultAttribute>(); + list.add(att); + OnapCommandResultAttribute a1 = new OnapCommandResultAttribute(); + a1.setName("param1"); + a1.setDescription("description1"); + a1.setType(ParameterType.STRING); + a1.setValues(new ArrayList<String>(Arrays.asList(new String[] { "value1" }))); + + list.add(a1); + res.setRecords(list); + res.setScope(OnapCommandResultAttributeScope.LONG); + res.setType(ResultType.CSV); + + String expRes = "param,param1\r\n"; + String result = res.print(); + assertEquals(expRes, result); + + } + + @Test + @Ignore + public void commandResultPrintPortraitCsvTest() throws OnapCommandException { + OnapCommandResult res = new OnapCommandResult(); + res.setDebugInfo("debugInfo"); + res.setIncludeSeparator(true); + res.setIncludeTitle(true); + res.setOutput("Output"); + res.setPrintDirection(PrintDirection.PORTRAIT); + + OnapCommandResultAttribute att = new OnapCommandResultAttribute(); + att.setName("param"); + att.setDescription("description"); + att.setType(ParameterType.STRING); + att.setValues(new ArrayList<String>(Arrays.asList(new String[] { "value" }))); + List<OnapCommandResultAttribute> list = new ArrayList<OnapCommandResultAttribute>(); + list.add(att); + OnapCommandResultAttribute a1 = new OnapCommandResultAttribute(); + a1.setName("param1"); + a1.setDescription("description1"); + a1.setType(ParameterType.STRING); + a1.setValues(new ArrayList<String>(Arrays.asList(new String[] { "value1" }))); + + list.add(a1); + res.setRecords(list); + res.setScope(OnapCommandResultAttributeScope.LONG); + res.setType(ResultType.CSV); + String expRes = "property,value\r\nparam,value\r\n"; + String result = res.print(); + assertEquals(expRes, result); + } + + @Test + public void commandResultPrintPortraitTableTest() throws OnapCommandException { + OnapCommandResult res = new OnapCommandResult(); + res.setDebugInfo("debugInfo"); + res.setIncludeSeparator(true); + res.setIncludeTitle(true); + res.setOutput("Output"); + res.setPrintDirection(PrintDirection.PORTRAIT); + + OnapCommandResultAttribute att = new OnapCommandResultAttribute(); + att.setName("param"); + att.setDescription("description"); + att.setType(ParameterType.STRING); + att.setValues(new ArrayList<String>(Arrays.asList(new String[] { "value" }))); + + List<OnapCommandResultAttribute> list = new ArrayList<OnapCommandResultAttribute>(); + list.add(att); + res.setRecords(list); + res.setScope(OnapCommandResultAttributeScope.LONG); + res.setType(ResultType.TABLE); + String expRes = "+----------+--------+\n|property |value |\n+----------+--------+" + + "\n|param |value |\n+----------+--------+\n"; + + String result = res.print(); + + assertEquals(expRes, result); + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java b/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java new file mode 100644 index 00000000..0aa82979 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java @@ -0,0 +1,43 @@ +/* + * 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.output; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection; + +public class PrintDirectionTest { + @Test + public void printDirectionGetTest() { + + try { + assertTrue(PrintDirection.LANDSCAPE.equals(PrintDirection.get("landscape")) + && PrintDirection.PORTRAIT.equals(PrintDirection.get("portrait"))); + } catch (OnapCommandInvalidPrintDirection e) { + fail("Shouldn't have thrown this exception : " + e.getMessage()); + } + + try { + PrintDirection.get("name"); + } catch (OnapCommandInvalidPrintDirection e) { + assertTrue("0x0004::Print direction name is invalid".equals(e.getMessage())); + } + + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java b/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java new file mode 100644 index 00000000..3c4c5665 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java @@ -0,0 +1,42 @@ +/* + * 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.output; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ResultTypeTest { + @Test + public void resultTypeGetTest() { + assertTrue(ResultType.TABLE.equals(ResultType.get("table")) && ResultType.CSV.equals(ResultType.get("csv")) + && ResultType.JSON.equals(ResultType.get("json")) && ResultType.YAML.equals(ResultType.get("yaml")) + && ResultType.TEXT.equals(ResultType.get("text"))); + + } + + @Test + public void isTabularFormTest() { + assertTrue(ResultType.isTabularForm("table")); + } + + @Test + public void isTabularFormNotTest() { + assertFalse(ResultType.isTabularForm("text")); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java b/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java new file mode 100644 index 00000000..ae17d6d4 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java @@ -0,0 +1,82 @@ +/* + * 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.output.print; + +import static org.junit.Assert.assertEquals; + +import org.junit.Ignore; +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandOutputPrintingFailed; +import org.onap.cli.fw.output.PrintDirection; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class OnapCommandPrintTest { + + @Test + @Ignore + public void printCsvTest() throws OnapCommandOutputPrintingFailed { + OnapCommandPrint pr = new OnapCommandPrint(); + pr.setDirection(PrintDirection.LANDSCAPE); + pr.setPrintTitle(true); + pr.addColumn("name1", new ArrayList<String>(Arrays.asList(new String[] { "value1" }))); + String exp = "name1\r\n"; + String result = pr.printCsv(); + assertEquals(exp, result); + } + + @Test + public void printTableTest() throws OnapCommandOutputPrintingFailed { + OnapCommandPrint pr = new OnapCommandPrint(); + List<String> getColumnsData = new ArrayList<String>(); + pr.setDirection(PrintDirection.LANDSCAPE); + pr.setPrintTitle(true); + pr.addColumn("name2", new ArrayList<String>(Arrays.asList(new String[] { "value2" }))); + String exp = "+--------+\n|name2 |\n+--------+\n|value2 |\n+--------+\n"; + String result = pr.printTable(true); + getColumnsData = pr.getColumn("name2"); + assertEquals(exp, result); + } + + @Test + public void printTableNullColumnHeaderTest() throws OnapCommandOutputPrintingFailed { + OnapCommandPrint pr = new OnapCommandPrint(); + List<String> getColumnsData = new ArrayList<String>(); + pr.setDirection(PrintDirection.LANDSCAPE); + pr.setPrintTitle(true); + pr.addColumn("name2", new ArrayList<String>(Arrays.asList(new String[] { "value2" }))); + String exp = "+--------+\n|name2 |\n+--------+\n|value2 |\n+--------+\n"; + String result = pr.printTable(true); + getColumnsData = pr.getColumn(null); + assertEquals(exp, result); + } + + @Test + public void printTableEmptyColumnValuesTest() throws OnapCommandOutputPrintingFailed { + OnapCommandPrint pr = new OnapCommandPrint(); + List<String> getColumnsData = new ArrayList<String>(); + pr.setDirection(PrintDirection.LANDSCAPE); + pr.setPrintTitle(true); + pr.addColumn("name2", new ArrayList<String>(Arrays.asList(new String[] { "" }))); + String exp = "+--------+\n|name2 |\n+--------+\n| |\n+--------+\n"; + String result = pr.printTable(true); + getColumnsData = pr.getColumn("name2"); + assertEquals(exp, result); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/output/print/TableGeneratorTest.java b/framework/src/test/java/org/onap/cli/fw/output/print/TableGeneratorTest.java new file mode 100644 index 00000000..f9ae0717 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/output/print/TableGeneratorTest.java @@ -0,0 +1,185 @@ +/* + * 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.output.print; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class TableGeneratorTest { + private TableGenerator table; + + @Before + public void setUp() throws Exception { + this.table = new TableGenerator(); + } + + @Test + public void printTableNoColumnTest() { + System.out.println("printTableNoColumnTest..."); + List<Object> row = new ArrayList<Object>(); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(row); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "\n\n\n"; + assertEquals(expected, result); + } + + @Test + public void printTableNoCellTest() { + System.out.println("printTableNoCellTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+----------+----------+\n|column1 |column2 |\n+----------+----------+\n"; + assertEquals(expected, result); + } + + @Test + public void printTableNullCellTest() { + + System.out.println("printTableNullCellTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + rows.add(Arrays.asList(new Object[] { "value1", null })); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+----------+----------+\n" + "|column1 |column2 |\n" + "+----------+----------+\n" + + "|value1 | |\n" + "+----------+----------+\n"; + assertEquals(expected, result); + + } + + @Test + public void printTableEmptyCellTest() { + System.out.println("printTableEmptyCellTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + rows.add(Arrays.asList(new Object[] { "value1", "" })); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+----------+----------+\n" + "|column1 |column2 |\n" + "+----------+----------+\n" + + "|value1 | |\n" + "+----------+----------+\n"; + assertEquals(expected, result); + } + + @Test + public void printTableNoCellBreakTest() { + System.out.println("printTableNoCellBreakTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + rows.add(Arrays.asList(new Object[] { "value1", "value2" })); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+----------+----------+\n" + "|column1 |column2 |\n" + "+----------+----------+\n" + + "|value1 |value2 |\n" + "+----------+----------+\n"; + assertEquals(expected, result); + } + + @Test + public void printTableCellBreakTest() { + System.out.println("printTableCellBreakTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + List<Object> list = new ArrayList<Object>(); + list.add("value1"); + list.add(new ArrayList<Object>( + Arrays.asList(new Object[] { "1234567891234567891234567891234567891234", "56789" }))); + rows.add(list); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+----------+------------------------------------------+\n" + + "|column1 |column2 |\n" + + "+----------+------------------------------------------+\n" + + "|value1 |1234567891234567891234567891234567891234 |\n" + + "| |56789 |\n" + + "+----------+------------------------------------------+\n"; + assertEquals(expected, result); + } + + @Test + public void printTableTwoCellBreakInSameRowTest() { + System.out.println("printTableTwoCellBreakInSameRowTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + List<Object> list = new ArrayList<Object>(); + list.add(new ArrayList<Object>( + Arrays.asList(new Object[] { "1234567891234567891234567891234567891234", "56789" }))); + list.add(new ArrayList<Object>( + Arrays.asList(new Object[] { "1234567891234567891234567891234567891234", "56789", "00" }))); + rows.add(list); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+------------------------------------------+------------------------------------------+\n" + + "|column1 |column2 |\n" + + "+------------------------------------------+------------------------------------------+\n" + + "|1234567891234567891234567891234567891234 |1234567891234567891234567891234567891234 |\n" + + "|56789 |56789 |\n" + + "| |00 |\n" + + "+------------------------------------------+------------------------------------------+\n"; + assertEquals(expected, result); + } + + @Test + public void printTableTwoCellBreakInDifferentRowTest() { + System.out.println("printTableTwoCellBreakInSameRowTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + List<Object> list1 = new ArrayList<Object>(); + list1.add("value1"); + list1.add(new ArrayList<Object>( + Arrays.asList(new Object[] { "1234567891234567891234567891234567891234", "56789" }))); + rows.add(list1); + List<Object> list2 = new ArrayList<Object>(); + list2.add(new ArrayList<Object>( + Arrays.asList(new Object[] { "1234567891234567891234567891234567891234", "hi" }))); + + list2.add("value2"); + rows.add(list2); + String result = table.generateTable(rows, true); + System.out.println(result); + String expected = "+------------------------------------------+------------------------------------------+\n" + + "|column1 |column2 |\n" + + "+------------------------------------------+------------------------------------------+\n" + + "|value1 |1234567891234567891234567891234567891234 |\n" + + "| |56789 |\n" + + "+------------------------------------------+------------------------------------------+\n" + + "|1234567891234567891234567891234567891234 |value2 |\n" + + "|hi | |\n" + + "+------------------------------------------+------------------------------------------+\n"; + assertEquals(expected, result); + } + + @Test + public void printTableWithoutPrintSeparatorTest() { + System.out.println("printTableWithoutPrintSeparatorTest..."); + List<List<Object>> rows = new ArrayList<List<Object>>(); + rows.add(Arrays.asList(new Object[] { "column1", "column2" })); + rows.add(Arrays.asList(new Object[] { "value1", "value2" })); + String result = table.generateTable(rows, false); + System.out.println(result); + String expected = "column1 column2 \nvalue1 value2 \n"; + assertEquals(expected, result); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/run/OnapCommandExecutorTest.java b/framework/src/test/java/org/onap/cli/fw/run/OnapCommandExecutorTest.java new file mode 100644 index 00000000..1236365c --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/run/OnapCommandExecutorTest.java @@ -0,0 +1,38 @@ +/* + * 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.run; + +import org.junit.Assert; +import org.junit.Test; + +public class OnapCommandExecutorTest { + + @Test + public void commandExecutorTest() { + OnapCommandExecutor exec = new OnapCommandExecutor(); + exec.setApi("api"); + exec.setClient("client"); + exec.setEntity("entity"); + exec.setException("exception"); + exec.setMethod("method"); + + Assert.assertTrue( + exec.getApi().equals("api") && exec.getClient().equals("client") && exec.getEntity().equals("entity") + && exec.getMethod().equals("method") && exec.getException().equals("exception")); + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java b/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java new file mode 100644 index 00000000..4c48683b --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java @@ -0,0 +1,103 @@ +/* + * 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.schema; + +import org.junit.Test; +import org.onap.cli.fw.error.OnapCommandInvalidSchema; +import org.yaml.snakeyaml.scanner.ScannerException; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; + +public class ValidateSchemaTest { + + @Test(expected = OnapCommandInvalidSchema.class) + public void invalidateTest1() throws OnapCommandInvalidSchema { + new SchemaValidator(new File("fdsfds")); + new SchemaValidator(new File("fdsfds.yaml")); + } + + @Test(expected = OnapCommandInvalidSchema.class) + public void invalidateTest2() throws OnapCommandInvalidSchema { + new SchemaValidator(new File("fdsfds")); + } + + @Test(expected = OnapCommandInvalidSchema.class) + public void invalidateTest4() throws OnapCommandInvalidSchema { + new SchemaValidator( + new File(ValidateSchemaTest.class.getClassLoader().getResource("onap.properties").getFile())); + } + + @Test(expected = OnapCommandInvalidSchema.class) + public void invalidateTest5() throws OnapCommandInvalidSchema { + new SchemaValidator(new File( + ValidateSchemaTest.class.getClassLoader().getResource("schema-invalid-file-null.yaml").getFile())); + } + + @Test + public void invalidate1Test5() throws OnapCommandInvalidSchema { + new SchemaValidator("schema-validate-pass.yaml"); + } + + @Test(expected = ScannerException.class) + public void invalidateTest3() throws OnapCommandInvalidSchema { + new SchemaValidator( + new File(ValidateSchemaTest.class.getClassLoader().getResource("schema-invalid-file.yaml").getFile())); + } + + @Test + public void validateTest() throws OnapCommandInvalidSchema { + new SchemaValidator( + new File(ValidateSchemaTest.class.getClassLoader().getResource("schema-validate-http.yaml").getFile())) + .validate(); + + new SchemaValidator( + new File(ValidateSchemaTest.class.getClassLoader().getResource("schema-validate-basic.yaml").getFile())) + .validate(); + new SchemaValidator(new File(ValidateSchemaTest.class.getClassLoader() + .getResource("schema-validate-invalidschematype.yaml").getFile())).validate(); + new SchemaValidator( + new File(ValidateSchemaTest.class.getClassLoader().getResource("schema-validate-invalid.yaml").getFile())) + .validate(); + new SchemaValidator( + new File(ValidateSchemaTest.class.getClassLoader().getResource("schema-validate-pass.yaml").getFile())) + .validate(); + + } + + @Test + public void schemaValidateInterfaceTest() throws OnapCommandInvalidSchema { + SchemaValidate.attributeNameExist("name", "section"); + SchemaValidate.emptyValue("section", "attribute"); + SchemaValidate.defaultYamlSchema("section"); + SchemaValidate.emptySection("section"); + SchemaValidate.invalidAttributeScope("name", new ArrayList<String>()); + SchemaValidate.invalidAttrType("name", "section", new ArrayList<String>()); + SchemaValidate.invalidBooleanValueMessage("section", "attribute", "value"); + SchemaValidate.invalidRequestParam("subSection", "attribute"); + SchemaValidate.invalidSections(new HashSet<String>(), new ArrayList<String>(), new ArrayList<String>()); + SchemaValidate.attributeScopeEmpty("fsdf"); + SchemaValidate.invalidType("section", "attribute", new ArrayList<String>()); + SchemaValidate.longOptionExist("name"); + SchemaValidate.shortOptionExist("name"); + SchemaValidate.optionExist("option", "attrValue", "name"); + SchemaValidate.optionDefaultExist("option", "attrValue", "name", new HashSet<String>()); + SchemaValidate.nameExist("name", "section"); + SchemaValidate.mandatoryAttrEmpty("param", "section"); + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/utils/FileUtil.java b/framework/src/test/java/org/onap/cli/fw/utils/FileUtil.java new file mode 100644 index 00000000..7da6230f --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/utils/FileUtil.java @@ -0,0 +1,55 @@ +/* + * 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.utils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil { + + /** + * Load file. + * @param srcName dir + * @return string + * @throws IOException exception + */ + public static String loadResource(String srcName) throws IOException { + ClassLoader classLoader = FileUtil.class.getClassLoader(); + File file = new File(classLoader.getResource(srcName).getFile()); + BufferedReader br = new BufferedReader(new FileReader(file)); + StringBuilder sb = new StringBuilder(""); + if (br != null) { + try { + + String line = br.readLine(); + + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + } finally { + br.close(); + } + } + + return sb.toString(); + + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java b/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java new file mode 100644 index 00000000..b74027a0 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java @@ -0,0 +1,481 @@ +/* + * 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.utils; + + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import mockit.Invocation; +import mockit.Mock; +import mockit.MockUp; + +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.onap.cli.fw.OnapCommand; +import org.onap.cli.fw.OnapCommandSchema; +import org.onap.cli.fw.ad.OnapCredentials; +import org.onap.cli.fw.cmd.OnapHttpCommand; +import org.onap.cli.fw.cmd.OnapSwaggerCommand; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandHelpFailed; +import org.onap.cli.fw.error.OnapCommandHttpHeaderNotFound; +import org.onap.cli.fw.error.OnapCommandHttpInvalidResponseBody; +import org.onap.cli.fw.error.OnapCommandInvalidParameterType; +import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection; +import org.onap.cli.fw.error.OnapCommandInvalidResultAttributeScope; +import org.onap.cli.fw.error.OnapCommandInvalidSchema; +import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion; +import org.onap.cli.fw.error.OnapCommandParameterNameConflict; +import org.onap.cli.fw.error.OnapCommandParameterNotFound; +import org.onap.cli.fw.error.OnapCommandParameterOptionConflict; +import org.onap.cli.fw.error.OnapCommandSchemaNotFound; +import org.onap.cli.fw.http.HttpInput; +import org.onap.cli.fw.http.HttpResult; +import org.onap.cli.fw.input.OnapCommandParameter; +import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.output.OnapCommandResult; +import org.onap.cli.fw.run.OnapCommandExecutor; +import org.springframework.core.io.Resource; + + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class OnapCommandUtilsTest { + + @Test(expected = OnapCommandSchemaNotFound.class) + public void onapCommandUtilsInputStreamNullTest() throws OnapCommandException { + OnapCommandUtils.validateSchemaVersion("sample-test1-schema-http1.yaml", "1.0"); + } + + @Test + public void onapCommandUtilsInputStreamNotNullTest() throws OnapCommandException { + Map<String, ?> map = OnapCommandUtils.validateSchemaVersion("sample-test1-schema-http.yaml", "1.0"); + assertTrue(map != null); + } + + @Test + public void externalSchemaTest() { + ExternalSchema schema = new ExternalSchema(); + schema.setCmdName("cmdName"); + schema.setSchemaName("schemaName"); + schema.setVersion("version"); + + assertTrue("cmdName".equals(schema.getCmdName()) && "schemaName".equals(schema.getSchemaName()) + && "version".equals(schema.getVersion())); + } + + @Test + public void schemaFileNotFoundTest() throws OnapCommandException { + + Map<String, ?> map = OnapCommandUtils.validateSchemaVersion("sample-test-schema.yaml", "1.0"); + assertTrue(map.size() > 0); + } + + @Test + @Ignore + public void invalidSchemaFileTest() throws OnapCommandException { + Map<String, ?> map = null; + try { + map = OnapCommandUtils.validateSchemaVersion("sample-test-schema1.yaml", "1.0"); + } catch (OnapCommandInvalidSchemaVersion e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } catch (OnapCommandInvalidSchema e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } catch (OnapCommandSchemaNotFound e) { + assertEquals("0x0019::Command schema sample-test-schema1.yaml is not found", e.getMessage()); + } + } + + @Test + public void validateWrongSchemaVersionTest() throws OnapCommandException { + Map<String, ?> map = null; + try { + map = OnapCommandUtils.validateSchemaVersion("sample-test-invalid-schema.yaml", "1.0"); + } catch (OnapCommandInvalidSchemaVersion e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } catch (OnapCommandInvalidSchema e) { + assertTrue(e.getMessage().contains("0x0007::Command schema sample-test-invalid-schema.yaml is invalid")); + } catch (OnapCommandSchemaNotFound e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } + } + + @Test + public void validateSchemaVersionTest() throws OnapCommandException { + Map<String, ?> map = null; + try { + map = OnapCommandUtils.validateSchemaVersion("sample-test-schema.yaml", "1.1"); + } catch (OnapCommandInvalidSchemaVersion e) { + assertEquals("0x0008::Command schema onap_cmd_schema_version 1.0 is invalid or missing", e.getMessage()); + } catch (OnapCommandInvalidSchema e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } catch (OnapCommandSchemaNotFound e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } + } + + @Test + public void loadOnapCommandSchemaWithOutDefaultTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", false); + assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 9); + } + + @Test(expected = OnapCommandParameterNameConflict.class) + public void loadOnapCommandSchemaWithDuplicateNameTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-name.yaml", false); + } + + @Test(expected = OnapCommandParameterOptionConflict.class) + public void loadOnapCommandSchemaWithDuplicateShortOptionTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-shortoption.yaml", false); + } + + @Test(expected = OnapCommandParameterOptionConflict.class) + public void loadOnapCommandSchemaWithDuplicateLongOptionTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-longoption.yaml", false); + } + + @Test + public void loadOnapCommandSchemaWithDefaultTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", true); + assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() > 9); + + for (OnapCommandParameter com : cmd.getParameters()) { + com.setValue("value"); + } + + OnapCredentials cre = OnapCommandUtils.fromParameters(cmd.getParameters()); + assertTrue(cre != null); + Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters()); + assertTrue(map.size() == 19); + } + + @Test + public void loadSwaggerBasedSchemaExceptionTest() throws OnapCommandException { + OnapSwaggerCommand cmd = new OnapSwaggerBasedCommandSample(); + try { + OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml"); + } catch (OnapCommandInvalidSchema e) { + assertTrue(e.getMessage().contains("0x0007::Command schema sample-test-schema.yaml is invalid")); + } + } + + @Test + public void loadSwaggerBasedSchemaTest() throws OnapCommandException { + OnapSwaggerCommand cmd = new OnapSwaggerBasedCommandSample(); + try { + OnapCommandUtils.loadSchema(cmd, "sample-test-schema-swagger.yaml"); + OnapCommandExecutor exe = cmd.getExecutor(); + assertTrue(exe != null); + } catch (OnapCommandInvalidSchema e) { + assertTrue(e.getMessage().contains("0x0007::Command schema sample-test-schema.yaml is invalid")); + } + } + + @Test + public void loadHttpBasedSchemaExceptionTest() throws OnapCommandException { + OnapHttpCommand cmd = new OnapHttpCommandSample(); + cmd.setName("sample-test-http"); + try { + OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml"); + } catch (OnapCommandParameterNameConflict | OnapCommandParameterOptionConflict + | OnapCommandInvalidParameterType | OnapCommandInvalidPrintDirection + | OnapCommandInvalidResultAttributeScope | OnapCommandSchemaNotFound | OnapCommandInvalidSchema + | OnapCommandInvalidSchemaVersion e) { + assertTrue(e.getMessage().contains("0x0007::Command schema sample-test-schema.yaml is invalid")); + } + } + + @Test + public void loadHttpBasedSchemaTest() throws OnapCommandException { + OnapHttpCommand cmd = new OnapHttpCommandSample(); + cmd.setName("sample-create-http"); + try { + OnapCommandUtils.loadSchema(cmd, "sample-test-schema-http.yaml"); + assertTrue(cmd.getSuccessStatusCodes().size() == 2); + } catch (OnapCommandParameterNameConflict | OnapCommandParameterOptionConflict + | OnapCommandInvalidParameterType | OnapCommandInvalidPrintDirection + | OnapCommandInvalidResultAttributeScope | OnapCommandSchemaNotFound | OnapCommandInvalidSchema + | OnapCommandInvalidSchemaVersion e) { + fail("Test should not have thrown this exception : " + e.getMessage()); + } + } + + @Test + public void helpCommandTest() throws IOException, OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", true); + + String actualResult = OnapCommandUtils.help(cmd); + + String expectedHelp = FileUtil.loadResource("sample-cmd-test-help.txt"); + } + + @Test + public void findOnapCommandsTest() { + List<Class<OnapCommand>> cmds = OnapCommandUtils.findOnapCommands(); + assertTrue(cmds.size() == 3); + } + + @Test + public void sortTest() { + Set<String> set = new HashSet<String>(); + set.add("dbvc"); + set.add("bbvcb"); + set.add("aaa"); + set.add("c"); + set.add("z"); + List<String> list = OnapCommandUtils.sort(set); + assertEquals("[aaa, bbvcb, c, dbvc, z]", list.toString()); + } + + @Test + public void jsonFlattenTest() { + List<String> list = Arrays.asList(new String[] { "{\"menu1\": {\"id\": \"file1\",\"value\": \"File1\"}}" }); + List<String> list1 = OnapCommandUtils.jsonFlatten(list); + String expected = "[{\"menu1\":{\"id\":\"file1\",\"value\":\"File1\"}}]"; + assertEquals(expected, list1.toString()); + + } + + @Test + public void jsonFlattenExceptionTest() { + List<String> list = Arrays.asList(new String[] { "{\"menu1\"::{\"id\":\"file1\",\"value\":\"File1\"}}" }); + List<String> list1 = OnapCommandUtils.jsonFlatten(list); + String expected = "[{\"menu1\"::{\"id\":\"file1\",\"value\":\"File1\"}}]"; + assertEquals(expected, list1.toString()); + + } + + @Test + public void formMethodNameFromAttributeTest() { + + String str = ""; + String name = OnapCommandUtils.formMethodNameFromAttributeName(str, "test"); + + assertEquals("", name); + + str = null; + name = OnapCommandUtils.formMethodNameFromAttributeName(str, "test"); + + assertEquals(null, name); + + str = "test-get"; + name = OnapCommandUtils.formMethodNameFromAttributeName(str, ""); + assertEquals("TestGet", name); + + } + + @Test + public void populateParametersTest() throws OnapCommandException { + + HttpInput input = new HttpInput(); + input.setBody("body"); + input.setMethod("method"); + Map<String, String> mapHead = new HashMap<>(); + mapHead.put("key2", "${value2}"); + input.setReqHeaders(mapHead); + Map<String, String> query = new HashMap<>(); + query.put("key3", "{${value3}}"); + input.setReqQueries(query); + input.setUri("uri"); + + Map<String, OnapCommandParameter> params = new HashMap<>(); + OnapCommandParameter param = new OnapCommandParameter(); + param.setDefaultValue("defaultValue2"); + param.setParameterType(ParameterType.STRING); + params.put("value2", param); + OnapCommandParameter param1 = new OnapCommandParameter(); + param1.setDefaultValue("{\"defaultValue3\"}"); + param1.setParameterType(ParameterType.JSON); + params.put("value3", param1); + + HttpInput input1 = OnapCommandUtils.populateParameters(params, input); + String expected = "\nURL: uri\nMethod: method\nRequest Queries: {key3={\"defaultValue3\"}}\n" + + "Request Body: body\nRequest Headers: {key2=defaultValue2}\nRequest Cookies: {}\nbinaryData=false"; + assertEquals(expected, input1.toString()); + + input.setBody("${body}"); + + HttpInput input2 = null; + try { + input2 = OnapCommandUtils.populateParameters(params, input); + } catch (OnapCommandParameterNotFound e) { + assertEquals("0x0026::Command input parameter body is not valid", e.getMessage()); + } + + } + + @Test(expected = OnapCommandHttpHeaderNotFound.class) + public void populateOutputsTest() throws OnapCommandException { + HttpResult output = new HttpResult(); + output.setBody( + "{\"serviceName\":\"test\",\"version\":\"v1\",\"url\":\"/api/test/v1\",\"protocol\":\"REST\",\"visualRange\":\"1\",\"lb_policy\":\"hash\",\"nodes\":[{\"ip\":\"127.0.0.1\",\"port\":\"8012\",\"ttl\":0,\"nodeId\":\"test_127.0.0.1_8012\",\"expiration\":\"2017-02-10T05:33:25Z\",\"created_at\":\"2017-02-10T05:33:25Z\",\"updated_at\":\"2017-02-10T05:33:25Z\"}],\"status\":\"1\"}"); + Map<String, String> mapHead = new HashMap<>(); + mapHead.put("head1", "value1"); + output.setRespHeaders(mapHead); + output.setStatus(0); + + Map<String, String> params = new HashMap<>(); + params.put("head", "$h{head1}"); + params.put("body", "$b{$.serviceName}"); + params.put("key", "value"); + + Map<String, ArrayList<String>> input1 = OnapCommandUtils.populateOutputs(params, output); + assertEquals("{head=[value1], body=[test], key=[value]}", input1.toString()); + + params.put("body", "$b{{$.serviceName}"); + try { + input1 = OnapCommandUtils.populateOutputs(params, output); + } catch (OnapCommandHttpInvalidResponseBody e) { + assertEquals( + "0x0028::Http response body does not have json entry {$.serviceName, Missing property in path $['{$']", + e.getMessage()); + } + output.setBody("{}"); + input1 = OnapCommandUtils.populateOutputs(params, output); + params.put("head", "$h{head2}"); + output.setBody("{\"test\"}"); + input1 = OnapCommandUtils.populateOutputs(params, output); + } + + @Test(expected = OnapCommandException.class) + public void zendExceptionTest1() throws OnapCommandException { + + mockExternalResources(); + OnapCommandUtils.loadSchema(new OnapSwaggerBasedCommandSample(), "schemaName"); + } + + @Test(expected = OnapCommandException.class) + public void zendExceptionTest2() throws OnapCommandException { + + mockExternalResources(); + OnapCommandUtils.loadSchema(new OnapHttpCommandSample(), "schemaName", false); + } + + @Test(expected = OnapCommandException.class) + public void zendExceptionTest3() throws OnapCommandException { + + mockExternalResources(); + OnapCommandUtils.validateSchemaVersion("schemaName", "version"); + } + + @Test(expected = OnapCommandException.class) + public void zendExceptionTest4() throws OnapCommandException { + + mockExternalResources(); + OnapCommandUtils.loadExternalSchemasFromJson(); + } + + @Test(expected = OnapCommandException.class) + public void zendExceptionTest5() throws OnapCommandException { + + mockExternalResources(); + OnapCommandUtils.findAllExternalSchemas(); + } + + @Test(expected = OnapCommandException.class) + public void zendExceptionTest6() throws OnapCommandException { + + mockExternalResources(); + OnapCommandUtils.persist(new ArrayList<ExternalSchema>()); + } + + @Test(expected = OnapCommandHelpFailed.class) + public void zendExceptionHelpTest1() throws OnapCommandException { + + mockPrintMethodException(); + OnapCommand cmd = new OnapCommandSample(); + OnapCommandUtils.loadSchema(cmd, "sample-test-schema.yaml", true); + + OnapCommandUtils.help(cmd); + + } + + @OnapCommandSchema(name = "sample-test", schema = "sample-test-schema.yaml") + class OnapCommandSample extends OnapCommand { + @Override + protected void run() throws OnapCommandException { + } + } + + @OnapCommandSchema(name = "sample-swagger-test", schema = "sample-test-schema-swagger.yaml") + class OnapSwaggerBasedCommandSample extends OnapSwaggerCommand { + + @Override + protected void run() throws OnapCommandException { + } + } + + @OnapCommandSchema(name = "sample-http-test", schema = "sample-test-schema-http.yaml") + class OnapHttpCommandSample extends OnapHttpCommand { + + @Override + protected void run() throws OnapCommandException { + } + } + + private void mockExternalResources() { + new MockUp<OnapCommandUtils>() { + boolean isMock = true; + + @Mock + public Resource[] getExternalResources(Invocation inv, String pattern) throws IOException { + if (isMock) { + isMock = false; + throw new IOException(); + } else { + return inv.proceed(pattern); + } + } + }; + } + + private void mockPrintMethodException() { + new MockUp<OnapCommandResult>() { + boolean isMock = true; + + @Mock + public String print(Invocation inv) throws OnapCommandException { + if (isMock) { + isMock = false; + throw new OnapCommandException("", ""); + } else { + return inv.proceed(); + } + } + }; + } +} diff --git a/framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java b/framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java new file mode 100644 index 00000000..fa73ea6e --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java @@ -0,0 +1,42 @@ +/* + * 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.utils; + +import org.junit.Before; +import org.junit.Test; +import org.onap.cli.fw.OnapCommand; +import org.onap.cli.fw.OnapCommandRegistrar; +import org.onap.cli.fw.error.OnapCommandException; + + +public class OpenCommandRegistrarTest { + + @Before + public void setUp() throws Exception { + + } + + @Test + public void test() throws OnapCommandException { + OnapCommandRegistrar registrar = OnapCommandRegistrar.getRegistrar(); + OnapCommand cmd = registrar.get("sample-test"); + registrar.listCommands(); + registrar.getAllCommandToSchemaMap(); + cmd.printVersion(); + } + +} |