http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/809d64d7/geode-core/src/test/java/org/apache/geode/management/internal/cli/GfshParserJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/GfshParserJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/GfshParserJUnitTest.java deleted file mode 100644 index 44e99f4..0000000 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/GfshParserJUnitTest.java +++ /dev/null @@ -1,863 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You 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.apache.geode.management.internal.cli; - -import static org.junit.Assert.*; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.shell.core.CommandMarker; -import org.springframework.shell.core.Completion; -import org.springframework.shell.core.Converter; -import org.springframework.shell.core.MethodTarget; -import org.springframework.shell.core.Parser; -import org.springframework.shell.core.annotation.CliAvailabilityIndicator; -import org.springframework.shell.core.annotation.CliCommand; -import org.springframework.shell.core.annotation.CliOption; -import org.springframework.shell.event.ParseResult; - -import org.apache.geode.management.cli.CliMetaData; -import org.apache.geode.management.cli.CommandProcessingException; -import org.apache.geode.management.cli.ConverterHint; -import org.apache.geode.management.cli.Result; -import org.apache.geode.management.internal.cli.annotation.CliArgument; -import org.apache.geode.management.internal.cli.converters.StringArrayConverter; -import org.apache.geode.management.internal.cli.converters.StringListConverter; -import org.apache.geode.management.internal.cli.i18n.CliStrings; -import org.apache.geode.management.internal.cli.parser.SyntaxConstants; -import org.apache.geode.management.internal.cli.result.ResultBuilder; -import org.apache.geode.management.internal.security.ResourceOperation; -import org.apache.geode.security.ResourcePermission.Operation; -import org.apache.geode.security.ResourcePermission.Resource; -import org.apache.geode.test.junit.categories.UnitTest; - -/** - * GfshParserJUnitTest - Includes tests to check the parsing and auto-completion capabilities of - * {@link GfshParser} - */ -@Category(UnitTest.class) -public class GfshParserJUnitTest { - - private static final String COMMAND1_NAME = "command1"; - private static final String COMMAND1_NAME_ALIAS = "command1_alias"; - private static final String COMMAND2_NAME = "c2"; - - private static final String COMMAND1_HELP = "help for " + COMMAND1_NAME; - - // ARGUMENTS - private static final String ARGUMENT1_NAME = "argument1"; - private static final String ARGUMENT1_HELP = "help for argument1"; - private static final String ARGUMENT1_CONTEXT = "context for argument 1"; - private static final Completion[] ARGUMENT1_COMPLETIONS = - {new Completion("arg1"), new Completion("arg1alt")}; - private static final String ARGUMENT2_NAME = "argument2"; - private static final String ARGUMENT2_CONTEXT = "context for argument 2"; - private static final String ARGUMENT2_HELP = "help for argument2"; - private static final String ARGUMENT2_UNSPECIFIED_DEFAULT_VALUE = - "{unspecified default value for argument2}"; - private static final Completion[] ARGUMENT2_COMPLETIONS = - {new Completion("arg2"), new Completion("arg2alt")}; - - // OPTIONS - private static final String OPTION1_NAME = "option1"; - private static final String OPTION1_SYNONYM = "opt1"; - private static final String OPTION1_HELP = "help for option1"; - private static final String OPTION1_CONTEXT = "context for option1"; - private static final Completion[] OPTION1_COMPLETIONS = - {new Completion("option1"), new Completion("option1Alternate")}; - private static final String OPTION2_NAME = "option2"; - private static final String OPTION2_HELP = "help for option2"; - private static final String OPTION2_CONTEXT = "context for option2"; - private static final String OPTION2_SPECIFIED_DEFAULT_VALUE = - "{specified default value for option2}"; - private static final Completion[] OPTION2_COMPLETIONS = - {new Completion("option2"), new Completion("option2Alternate")}; - private static final String OPTION3_NAME = "option3"; - private static final String OPTION3_SYNONYM = "opt3"; - private static final String OPTION3_HELP = "help for option3"; - private static final String OPTION3_CONTEXT = "context for option3"; - private static final String OPTION3_UNSPECIFIED_DEFAULT_VALUE = - "{unspecified default value for option3}"; - private static final Completion[] OPTION3_COMPLETIONS = - {new Completion("option3"), new Completion("option3Alternate")}; - - private Method methodCommand1; - private Method methodTestParamConcat; - private Method methodTestMultiWordArg; - - private CommandManager commandManager; - private GfshParser parser; - - @Before - public void setUp() throws Exception { - methodCommand1 = Commands.class.getMethod("command1", String.class, String.class, String.class, - String.class, String.class); - methodTestParamConcat = Commands.class.getMethod("testParamConcat", String.class, - String[].class, List.class, Integer.class, String[].class); - methodTestMultiWordArg = - Commands.class.getMethod("testMultiWordArg", String.class, String.class); - - // Make sure no prior tests leave the CommandManager in a funky state - CommandManager.clearInstance(); - - commandManager = CommandManager.getInstance(false); - commandManager.add(Commands.class.newInstance()); - commandManager.add(SimpleConverter.class.newInstance()); - commandManager.add(StringArrayConverter.class.newInstance()); - commandManager.add(StringListConverter.class.newInstance()); - - // Set up the parser - parser = new GfshParser(commandManager); - - CliUtil.isGfshVM = false; - } - - @After - public void tearDown() { - CommandManager.clearInstance(); - } - - /** - * Tests the auto-completion capability of {@link GfshParser} with the method - * {@link GfshParser#complete(String, int, List)} - */ - @Test - public void testComplete() throws Exception { - // Get the names of the command - String[] command1Names = ((CliCommand) methodCommand1.getAnnotation(CliCommand.class)).value(); - - // Input contains an entirely different string - String input = "moc"; - List<String> completionCandidates = new ArrayList<String>(); - List<String> completionValues = new ArrayList<String>(); - parser.complete(input, input.length(), completionCandidates); - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains a string which is prefix - // of more than 1 command - input = "c"; - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // completions will come alphabetically sorted - completionValues.add(COMMAND2_NAME); - completionValues.add(COMMAND1_NAME); - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains only prefix of the command - // name which is not a prefix of other command. - // It may be the prefix for the synonym of command - input = command1Names[0].substring(0, 3); - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - completionValues.add(COMMAND1_NAME); - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains only the command name - input = command1Names[0]; - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the completions for argument1 - // For arguments, the formatted value will equal the actual arguments - // But the actual value will contain the ARGUMENT_SEPARATOR - for (Completion completion : ARGUMENT1_COMPLETIONS) { - completionValues.add(" " + completion.getValue()); - } - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name and prefix of first - // argument - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue().substring(0, 3); - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the completions for argument2 - // which have the provided first argument as the prefix - for (Completion completion : ARGUMENT1_COMPLETIONS) { - if (completion.getValue().startsWith(ARGUMENT1_COMPLETIONS[0].getValue().substring(0, 3))) { - completionValues.add(" " + completion.getValue()); - } - } - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument - // and first option - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION1_NAME; - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the values for the first option - for (Completion completion : OPTION1_COMPLETIONS) { - completionValues.add(SyntaxConstants.OPTION_VALUE_SPECIFIER + completion.getValue()); - } - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option and prefix of one of the values provided - // by the auto-completor. - input = command1Names[1] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER - + OPTION1_COMPLETIONS[0].getValue().substring(0, 2); - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the values for the first option - for (Completion completion : OPTION1_COMPLETIONS) { - if (completion.getValue().startsWith(OPTION1_COMPLETIONS[0].getValue().substring(0, 2))) { - completionValues.add(SyntaxConstants.OPTION_VALUE_SPECIFIER + completion.getValue()); - } - } - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option and one of the values provided - // by the auto-completor. - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue(); - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the remaining options - // As only first option is mandatory, we expect the - // the other non-mandatory options. - completionValues.add(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION2_NAME); - completionValues.add(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION3_NAME); - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option, one value for the option and value separator at - // the end - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue() - + SyntaxConstants.VALUE_SEPARATOR; - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the other values for completion - completionValues.add(SyntaxConstants.VALUE_SEPARATOR + OPTION1_COMPLETIONS[1].getValue()); - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option and both the values for the option - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue() - + SyntaxConstants.VALUE_SEPARATOR + OPTION1_COMPLETIONS[1].getValue(); - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect the remaining options - // As only first option is mandatory, we expect the - // the other non-mandatory options. - completionValues.add(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION2_NAME); - completionValues.add(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION3_NAME); - assertSimpleCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option, both the values for the option and valueSeparator - // at the end - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue() - + SyntaxConstants.VALUE_SEPARATOR + OPTION1_COMPLETIONS[1].getValue() - + SyntaxConstants.VALUE_SEPARATOR; - clearAndSimpleComplete(completionCandidates, completionValues, input, parser); - // Here we expect nothing for completion - assertSimpleCompletionValues(completionValues, completionCandidates); - } - - private void clearAndSimpleComplete(List<String> completionCandidates, - List<String> completionValues, String input, Parser parser) { - completionCandidates.clear(); - completionValues.clear(); - parser.complete(input, input.length(), completionCandidates); - } - - private void assertSimpleCompletionValues(List<String> expected, List<String> actual) { - assertEquals("Check size", expected.size(), actual.size()); - assertEquals(expected, actual); - } - - /** - * Tests the auto-completion capability of {@link GfshParser} with the method - * {@link GfshParser#completeAdvanced(String, int, List)} - */ - @Test - public void testCompleteAdvanced() throws Exception { - // Get the names of the command - String[] command1Names = ((CliCommand) methodCommand1.getAnnotation(CliCommand.class)).value(); - - // Input contains an entirely different string - String input = "moc"; - List<Completion> completionCandidates = new ArrayList<Completion>(); - List<Completion> completionValues = new ArrayList<Completion>(); - parser.completeAdvanced(input, input.length(), completionCandidates); - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains a string which is prefix - // of more than 1 command - input = "c"; - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // completions will come alphabetically sorted - completionValues.add(new Completion(COMMAND2_NAME)); - completionValues.add(new Completion(COMMAND1_NAME)); - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains only prefix of the command - // name which is not a prefix of other command. - // It may be the prefix for the synonym of command - input = command1Names[0].substring(0, 3); - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - completionValues.add(new Completion(COMMAND1_NAME)); - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains only the command name - input = command1Names[0]; - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the completions for argument1 - // For arguments, the formatted value will equal the actual arguments - // But the actual value will contain the ARGUMENT_SEPARATOR - for (Completion completion : ARGUMENT1_COMPLETIONS) { - completionValues.add( - new Completion(" " + completion.getValue(), completion.getFormattedValue(), null, 0)); - } - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name and prefix of first - // argument - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue().substring(0, 3); - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the completions for argument2 - // which have the provided first argument as the prefix - for (Completion completion : ARGUMENT1_COMPLETIONS) { - if (completion.getValue().startsWith(ARGUMENT1_COMPLETIONS[0].getValue().substring(0, 3))) { - completionValues.add( - new Completion(" " + completion.getValue(), completion.getFormattedValue(), null, 0)); - } - } - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument - // and first option - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION1_NAME; - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the values for the first option - for (Completion completion : OPTION1_COMPLETIONS) { - completionValues - .add(new Completion(SyntaxConstants.OPTION_VALUE_SPECIFIER + completion.getValue(), - completion.getValue(), null, 0)); - } - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option and prefix of one of the values provided - // by the auto-completor. - input = command1Names[1] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER - + OPTION1_COMPLETIONS[0].getValue().substring(0, 2); - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the values for the first option - for (Completion completion : OPTION1_COMPLETIONS) { - if (completion.getValue().startsWith(OPTION1_COMPLETIONS[0].getValue().substring(0, 2))) { - completionValues - .add(new Completion(SyntaxConstants.OPTION_VALUE_SPECIFIER + completion.getValue(), - completion.getValue(), null, 0)); - } - } - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option and one of the values provided - // by the auto-completor. - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue(); - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the remaining options - // As only first option is mandatory, we expect the - // the other non-mandatory options. - completionValues.add(new Completion(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION2_NAME, - OPTION2_NAME, null, 0)); - completionValues.add(new Completion(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION3_NAME, - OPTION3_NAME, null, 0)); - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option, one value for the option and value separator at - // the end - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue() - + SyntaxConstants.VALUE_SEPARATOR; - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the other values for completion - completionValues - .add(new Completion(SyntaxConstants.VALUE_SEPARATOR + OPTION1_COMPLETIONS[1].getValue(), - OPTION1_COMPLETIONS[1].getValue(), null, 0)); - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option and both the values for the option - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue() - + SyntaxConstants.VALUE_SEPARATOR + OPTION1_COMPLETIONS[1].getValue(); - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect the remaining options - // As only first option is mandatory, we expect the - // the other non-mandatory options. - completionValues.add(new Completion(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION2_NAME, - OPTION2_NAME, null, 0)); - completionValues.add(new Completion(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION3_NAME, - OPTION3_NAME, null, 0)); - assertAdvancedCompletionValues(completionValues, completionCandidates); - - // Input contains command name, first argument, second argument, - // first option, both the values for the option and valueSeparator - // at the end - input = command1Names[0] + " " + ARGUMENT1_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + ARGUMENT2_COMPLETIONS[0].getValue() - + SyntaxConstants.ARGUMENT_SEPARATOR + " " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + OPTION1_COMPLETIONS[0].getValue() - + SyntaxConstants.VALUE_SEPARATOR + OPTION1_COMPLETIONS[1].getValue() - + SyntaxConstants.VALUE_SEPARATOR; - clearAndAdvancedComplete(completionCandidates, completionValues, input, parser); - // Here we expect nothing for completion - assertAdvancedCompletionValues(completionValues, completionCandidates); - } - - private void clearAndAdvancedComplete(List<Completion> completionCandidates, - List<Completion> completionValues, String input, Parser parser) { - completionCandidates.clear(); - completionValues.clear(); - parser.completeAdvanced(input, input.length(), completionCandidates); - } - - private void assertAdvancedCompletionValues(List<Completion> expected, List<Completion> actual) { - assertEquals("Check size", expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - assertEquals("Check completion value no." + i + ". Expected(" + expected.get(i) - + ") & Actual(" + actual.get(i) + ").", expected.get(i).getValue(), - actual.get(i).getValue()); - if (expected.get(i).getFormattedValue() != null) { - assertEquals( - "Check completion formatted value no." + i + ". Expected(" - + expected.get(i).getFormattedValue() + ") & Actual(" - + actual.get(i).getFormattedValue() + ").", - expected.get(i).getFormattedValue(), actual.get(i).getFormattedValue()); - } - } - } - - /** - * Test for checking parsing of {@link GfshParser} with method {@link GfshParser#parse(String)} - * <p> - * Does not include testing for multiple values as this change is still pending in spring-shell - */ - @Test - public void testParse() throws Exception { - // Get the names of the command - String[] command1Names = ((CliCommand) methodCommand1.getAnnotation(CliCommand.class)).value(); - - // Input contains an entirely different string - String input = "moc"; - ParseResult parse = null; - CommandProcessingException expectedException = null; - try { - parse = parser.parse(input); - } catch (CommandProcessingException expected) { - expectedException = expected; - } finally { - assertNotNull("Expecting a " + CommandProcessingException.class - + " for an invalid command name: " + input, expectedException); - assertEquals( - "CommandProcessingException type doesn't match. " + "Actual(" - + expectedException.getErrorType() + ") & Expected(" - + CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE + ") ", - expectedException.getErrorType(), - CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE); - } - - // Input contains a string which is prefix - // of more than 1 command - input = "c"; - expectedException = null; - try { - parse = parser.parse(input); - } catch (CommandProcessingException e) { - expectedException = e; - } finally { - assertNotNull("Expecting a " + CommandProcessingException.class - + " for an invalid/incomplete command name: " + input, expectedException); - assertEquals( - "CommandProcessingException type doesn't match. Actual(" - + expectedException.getErrorType() + ") & Expected(" - + CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE + ") ", - expectedException.getErrorType(), - CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE); - } - - // Input contains only prefix of the command - // name which is not a prefix of other command. - // It may be the prefix for the synonym of command - input = "com"; - expectedException = null; - try { - parse = parser.parse(input); - } catch (CommandProcessingException expected) { - expectedException = expected; - } finally { - // FIXME - Nikhil/Abhishek prefix shouldn't work - assertNotNull("Expecting a " + CommandProcessingException.class - + " for an invalid/incomplete command name: " + input, expectedException); - assertEquals( - "CommandProcessingException type doesn't match. Actual(" - + expectedException.getErrorType() + ") & Expected(" - + CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE + ") ", - expectedException.getErrorType(), - CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE); - } - - // Input contains only command name - input = command1Names[0]; - expectedException = null; - try { - parse = parser.parse(input); - } catch (CommandProcessingException expected) { - expectedException = expected; - } finally { - assertNotNull("Expecting a " + CommandProcessingException.class - + " for an invalid/incomplete command name: " + input, expectedException); - assertEquals( - "CommandProcessingException type doesn't match. Actual(" - + expectedException.getErrorType() + ") & Expected(" - + CommandProcessingException.REQUIRED_ARGUMENT_MISSING + ") ", - CommandProcessingException.REQUIRED_ARGUMENT_MISSING, expectedException.getErrorType()); - } - - // Input contains first argument and first option with value - input = command1Names[0] + " ARGUMENT1_VALUE " + SyntaxConstants.LONG_OPTION_SPECIFIER - + OPTION1_NAME + SyntaxConstants.OPTION_VALUE_SPECIFIER + "somevalue"; - parse = parser.parse(input); - assertNotNull(parse); - assertEquals("Check ParseResult method", parse.getMethod(), methodCommand1); - assertEquals("Check no. of method arguments", 5, parse.getArguments().length); - assertEquals("Check argument1", "ARGUMENT1_VALUE", parse.getArguments()[0]); - assertEquals("Check argument2", ARGUMENT2_UNSPECIFIED_DEFAULT_VALUE, parse.getArguments()[1]); - assertEquals("Check option1 value", "somevalue", parse.getArguments()[2]); - assertEquals("Check option2 value", null, parse.getArguments()[3]); - assertEquals("Check option3 value", OPTION3_UNSPECIFIED_DEFAULT_VALUE, parse.getArguments()[4]); - - // Input contains only both arguments but is terminated by long option - // specifiers. These hyphens at the end are ignored by the parser - input = command1Names[1] + " ARGUMENT1_VALUE? ARGUMENT2_VALUE -- ----------"; - try { - parse = parser.parse(input); - } catch (CommandProcessingException expected) { - expectedException = expected; - } finally { - assertNotNull("Expecting a " + CommandProcessingException.class - + " for an invalid/incomplete command name: " + input, expectedException); - // assertEquals("CommandProcessingException type doesn't match. Actual(" - // + expectedException.getErrorType() + ") & Expected(" - // + CommandProcessingException.REQUIRED_OPTION_MISSING + ") ", - // expectedException.getErrorType(), - // CommandProcessingException.REQUIRED_OPTION_MISSING); - } - - // Input contains both arguments. The first option is specified with value - // The second is specified without value and the third option is not - // specified - input = command1Names[1] + " ARGUMENT1_VALUE? ARGUMENT2_VALUE " - + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION1_NAME - + SyntaxConstants.OPTION_VALUE_SPECIFIER + "option1value" + " " - + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION2_NAME; - parse = parser.parse(input); - assertNotNull(parse); - assertEquals("Check ParseResult method", parse.getMethod(), methodCommand1); - assertEquals("Check no. of method arguments", 5, parse.getArguments().length); - assertEquals("Check argument1", "ARGUMENT1_VALUE", parse.getArguments()[0]); - assertEquals("Check argument2", "ARGUMENT2_VALUE", parse.getArguments()[1]); - assertEquals("Check option1 value", "option1value", parse.getArguments()[2]); - assertEquals("Check option2 value", OPTION2_SPECIFIED_DEFAULT_VALUE, parse.getArguments()[3]); - assertEquals("Check option3 value", OPTION3_UNSPECIFIED_DEFAULT_VALUE, parse.getArguments()[4]); - - // Input contains both arguments. All the three options - // are specified with values - input = command1Names[1] + " ARGUMENT1_VALUE? ARGUMENT2_VALUE " - + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION1_SYNONYM - + SyntaxConstants.OPTION_VALUE_SPECIFIER + "option1value" + " " - + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION2_NAME - + SyntaxConstants.OPTION_VALUE_SPECIFIER + "option2value" + " " - + SyntaxConstants.LONG_OPTION_SPECIFIER + OPTION3_NAME - + SyntaxConstants.OPTION_VALUE_SPECIFIER + "option3value"; - parse = parser.parse(input); - assertNotNull(parse); - assertEquals("Check ParseResult method", parse.getMethod(), methodCommand1); - assertEquals("Check no. of method arguments", 5, parse.getArguments().length); - assertEquals("Check argument1", "ARGUMENT1_VALUE", parse.getArguments()[0]); - assertEquals("Check argument2", "ARGUMENT2_VALUE", parse.getArguments()[1]); - assertEquals("Check option1 value", "option1value", parse.getArguments()[2]); - assertEquals("Check option2 value", "option2value", parse.getArguments()[3]); - assertEquals("Check option3 value", "option3value", parse.getArguments()[4]); - - // Test concatenation of options when they appear more than once in the command - String command = - "testParamConcat --string=string1 --stringArray=1,2 --stringArray=3,4 --stringList=11,12,13 --integer=10 --stringArray=5 --stringList=14,15"; - ParseResult parseResult = parser.parse(command); - assertNotNull(parseResult); - assertEquals("Check ParseResult method", parseResult.getMethod(), methodTestParamConcat); - assertEquals("Check no. of method arguments", 5, parseResult.getArguments().length); - Object[] arguments = parseResult.getArguments(); - assertEquals(arguments[0], "string1"); - assertEquals(((String[]) arguments[1])[0], "1"); - assertEquals(((String[]) arguments[1])[1], "2"); - assertEquals(((String[]) arguments[1])[2], "3"); - assertEquals(((String[]) arguments[1])[3], "4"); - assertEquals(((String[]) arguments[1])[4], "5"); - assertEquals(((List) arguments[2]).get(0), "11"); - assertEquals(((List) arguments[2]).get(1), "12"); - assertEquals(((List) arguments[2]).get(2), "13"); - assertEquals(((List) arguments[2]).get(3), "14"); - assertEquals(((List) arguments[2]).get(4), "15"); - assertEquals(arguments[3], 10); - - // Test concatenation of options when they appear more than once in the command - command = "testParamConcat --stringArray=1,2 --stringArray=\'3,4\'"; - parseResult = parser.parse(command); - assertNotNull(parseResult); - assertEquals("Check ParseResult method", parseResult.getMethod(), methodTestParamConcat); - assertEquals("Check no. of method arguments", 5, parseResult.getArguments().length); - arguments = parseResult.getArguments(); - assertEquals(((String[]) arguments[1])[0], "1"); - assertEquals(((String[]) arguments[1])[1], "2"); - assertEquals(((String[]) arguments[1])[2], "3,4"); - - command = - "testParamConcat --string=\"1\" --colonArray=2:3:4 --stringArray=5,\"6,7\",8 --stringList=\"9,10,11,12\""; - parseResult = parser.parse(command); - assertNotNull(parseResult); - assertEquals("Check ParseResult method", parseResult.getMethod(), methodTestParamConcat); - assertEquals("Check no. of method arguments", 5, parseResult.getArguments().length); - arguments = parseResult.getArguments(); - assertEquals(arguments[0], "1"); - assertEquals(((String[]) arguments[1])[0], "5"); - assertEquals(((String[]) arguments[1])[1], "6,7"); - assertEquals(((String[]) arguments[1])[2], "8"); - assertEquals(((List) arguments[2]).get(0), "9,10,11,12"); - assertEquals(((String[]) arguments[4])[0], "2"); - assertEquals(((String[]) arguments[4])[1], "3"); - assertEquals(((String[]) arguments[4])[2], "4"); - - // try { - // command = "testParamConcat --string=string1 --stringArray=1,2 --string=string2"; - // parseResult = parser.parse(command); - // fail("Should have received a CommandProcessingException due to 'string' being specified - // twice"); - // } catch (CommandProcessingException expected) { - // // Expected - // } - - command = "testMultiWordArg this is just one argument?this is a second argument"; - parseResult = parser.parse(command); - assertNotNull(parseResult); - assertEquals("Check ParseResult method", parseResult.getMethod(), methodTestMultiWordArg); - assertEquals("Check no. of method arguments", 2, parseResult.getArguments().length); - arguments = parseResult.getArguments(); - assertEquals(arguments[0], "this is just one argument"); - assertEquals(arguments[1], "this is a second argument"); - } - - @Test - public void testDefaultAvailabilityMessage() throws Exception { - checkAvailabilityMessage(new AvailabilityCommands(), AvailabilityCommands.C2_NAME, - AvailabilityCommands.C2_MSG_UNAVAILABLE, AvailabilityCommands.C2_PROP); - } - - @Ignore("This test was not previously enabled and it fails. Is it valid?") - @Test - public void testCustomAvailabilityMessage() throws Exception { - checkAvailabilityMessage(new AvailabilityCommands(), AvailabilityCommands.C1_NAME, - AvailabilityCommands.C1_MSG_UNAVAILABLE, AvailabilityCommands.C1_PROP); - } - - public void checkAvailabilityMessage(CommandMarker availabilityCommands, String commandString, - String unavailableMessage, String availabiltyBooleanProp) throws Exception { - CommandManager cmdManager = CommandManager.getInstance(false); - cmdManager.add(availabilityCommands); - - GfshParser parser = new GfshParser(cmdManager); - ParseResult parseResult = null; - - // Case 1: Command is not available - try { - parseResult = parser.parse(commandString); - } catch (CommandProcessingException e) { - String actualMessage = e.getMessage(); - String expectedMessage = - CliStrings.format(CliStrings.GFSHPARSER__MSG__0_IS_NOT_AVAILABLE_REASON_1, - new Object[] {commandString, unavailableMessage}); - assertEquals("1. Unavailability message [" + actualMessage + "] is not as expected[" - + expectedMessage + "].", actualMessage, expectedMessage); - } - - // Case 2: Command is 'made' available - try { - System.setProperty(availabiltyBooleanProp, "true"); - parseResult = parser.parse(commandString); - assertNotNull("ParseResult should not be null for available command.", parseResult); - } finally { - System.clearProperty(availabiltyBooleanProp); - } - - // Case 3: Command is not available again - try { - parseResult = parser.parse(commandString); - } catch (CommandProcessingException e) { - String actualMessage = e.getMessage(); - String expectedMessage = - CliStrings.format(CliStrings.GFSHPARSER__MSG__0_IS_NOT_AVAILABLE_REASON_1, - new Object[] {commandString, unavailableMessage}); - assertEquals("2. Unavailabilty message [" + actualMessage + "] is not as expected[" - + expectedMessage + "].", actualMessage, expectedMessage); - } - } - - static class Commands implements CommandMarker { - - @CliCommand(value = {COMMAND1_NAME, COMMAND1_NAME_ALIAS}, help = COMMAND1_HELP) - @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) - public static String command1( - @CliArgument(name = ARGUMENT1_NAME, argumentContext = ARGUMENT1_CONTEXT, - help = ARGUMENT1_HELP, mandatory = true) String argument1, - @CliArgument(name = ARGUMENT2_NAME, argumentContext = ARGUMENT2_CONTEXT, - help = ARGUMENT2_HELP, mandatory = false, - unspecifiedDefaultValue = ARGUMENT2_UNSPECIFIED_DEFAULT_VALUE, - systemProvided = false) String argument2, - @CliOption(key = {OPTION1_NAME, OPTION1_SYNONYM}, help = OPTION1_HELP, mandatory = true, - optionContext = OPTION1_CONTEXT) String option1, - @CliOption(key = {OPTION2_NAME}, help = OPTION2_HELP, mandatory = false, - optionContext = OPTION2_CONTEXT, - specifiedDefaultValue = OPTION2_SPECIFIED_DEFAULT_VALUE) String option2, - @CliOption(key = {OPTION3_NAME, OPTION3_SYNONYM}, help = OPTION3_HELP, mandatory = false, - optionContext = OPTION3_CONTEXT, - unspecifiedDefaultValue = OPTION3_UNSPECIFIED_DEFAULT_VALUE) String option3) { - return null; - } - - @CliCommand(value = {COMMAND2_NAME}) - @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) - public static String command2() { - return null; - } - - @CliCommand(value = {"testParamConcat"}) - @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) - public static Result testParamConcat(@CliOption(key = {"string"}) String string, - @CliOption(key = {"stringArray"}) @CliMetaData(valueSeparator = ",") String[] stringArray, - @CliOption(key = {"stringList"}, optionContext = ConverterHint.STRING_LIST) @CliMetaData( - valueSeparator = ",") List<String> stringList, - @CliOption(key = {"integer"}) Integer integer, - @CliOption(key = {"colonArray"}) @CliMetaData(valueSeparator = ":") String[] colonArray) { - return null; - } - - @CliCommand(value = {"testMultiWordArg"}) - @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) - public static Result testMultiWordArg(@CliArgument(name = "arg1") String arg1, - @CliArgument(name = "arg2") String arg2) { - return null; - } - } - - static class SimpleConverter implements Converter<String> { - - @Override - public boolean supports(Class<?> type, String optionContext) { - if (type.isAssignableFrom(String.class)) { - return true; - } - return false; - } - - @Override - public String convertFromText(String value, Class<?> targetType, String optionContext) { - return value; - } - - @Override - public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, - String existingData, String context, MethodTarget target) { - if (context.equals(ARGUMENT1_CONTEXT)) { - for (Completion completion : ARGUMENT1_COMPLETIONS) { - completions.add(completion); - } - } else if (context.equals(ARGUMENT2_CONTEXT)) { - for (Completion completion : ARGUMENT2_COMPLETIONS) { - completions.add(completion); - } - } else if (context.equals(OPTION1_CONTEXT)) { - for (Completion completion : OPTION1_COMPLETIONS) { - completions.add(completion); - } - } - return true; - } - } - - public static class AvailabilityCommands implements CommandMarker { - - static final String C1_NAME = "C1"; - static final String C1_PROP = C1_NAME + "-available"; - static final String C1_MSG_UNAVAILABLE = "Requires " + C1_PROP + "=true"; - static final String C1_MSG_AVAILABLE = C1_NAME + " is available."; - - static final String C2_NAME = "C2"; - static final String C2_PROP = C2_NAME + "-available"; - static final String C2_MSG_UNAVAILABLE = - CliStrings.AVAILABILITYTARGET_MSG_DEFAULT_UNAVAILABILITY_DESCRIPTION; - static final String C2_MSG_AVAILABLE = C2_NAME + " is available."; - - @CliCommand(value = {C1_NAME}) - @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) - public Result command1() { - return ResultBuilder.createInfoResult(C1_MSG_AVAILABLE); - } - - @CliCommand(value = {C2_NAME}) - @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ) - public Result command2() { - return ResultBuilder.createInfoResult(C2_MSG_AVAILABLE); - } - - @CliAvailabilityIndicator(C1_NAME) - public boolean isCommand1Available() { - return Boolean.getBoolean(C1_PROP); - } - - @CliAvailabilityIndicator(C2_NAME) - public boolean isCommand2Available() { - return Boolean.getBoolean(C2_PROP); - } - } -}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/809d64d7/geode-core/src/test/java/org/apache/geode/management/internal/cli/JoptOptionParserTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/JoptOptionParserTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/JoptOptionParserTest.java deleted file mode 100644 index 9815a9c..0000000 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/JoptOptionParserTest.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You 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.apache.geode.management.internal.cli; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.Mockito.*; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; - -import org.apache.geode.management.internal.cli.exceptions.CliCommandOptionException; -import org.apache.geode.management.internal.cli.exceptions.CliCommandOptionMissingException; -import org.apache.geode.management.internal.cli.exceptions.CliCommandOptionNotApplicableException; -import org.apache.geode.management.internal.cli.parser.Argument; -import org.apache.geode.management.internal.cli.parser.Option; -import org.apache.geode.management.internal.cli.parser.OptionSet; -import org.apache.geode.management.internal.cli.parser.jopt.JoptOptionParser; -import org.apache.geode.test.junit.categories.UnitTest; - -@Category(UnitTest.class) -@RunWith(JUnitParamsRunner.class) -public class JoptOptionParserTest { - - private JoptOptionParser emptyOptionParser; - private OptionSet emptyOptionSet; - - private Argument requiredArgument; - private Argument optionalArgument; - - private Option requiredOption; - private Option optionalOption; - - private JoptOptionParser simpleOptionParser; - private JoptOptionParser exampleOptionParser; - - @Before - public void setUp() throws Exception { - this.emptyOptionParser = new JoptOptionParser(); - this.emptyOptionSet = new OptionSet(); - defineSimpleOptionParser(); - defineExampleOptionParser(); - } - - @Test - public void getArgumentsIsEmptyByDefault() throws Exception { - assertThat(this.emptyOptionParser.getArguments()).isEmpty(); - } - - @Test - public void getOptionsIsNullByDefault() throws Exception { - assertThat(this.emptyOptionParser.getOptions()).isNull(); - } - - @Test - public void parseNullReturnsDefaultOptionSet() throws Exception { - OptionSet optionSet = this.emptyOptionParser.parse(null); - assertThat(optionSet.areArgumentsPresent()).isEqualTo(emptyOptionSet.areArgumentsPresent()); - assertThat(optionSet.areOptionsPresent()).isEqualTo(emptyOptionSet.areOptionsPresent()); - assertThat(optionSet.getNoOfSpacesRemoved()).isEqualTo(emptyOptionSet.getNoOfSpacesRemoved()); - assertThat(optionSet.getSplit()).isEqualTo(emptyOptionSet.getSplit()); - assertThat(optionSet.getNoOfSpacesRemoved()).isEqualTo(emptyOptionSet.getNoOfSpacesRemoved()); - assertThat(optionSet.getUserInput()).isEqualTo(""); // emptyOptionSet.getUserInput()); - assertThat(optionSet.getValue((Argument) null)) - .isEqualTo(emptyOptionSet.getValue((Argument) null)); - assertThat(optionSet.getValue((Option) null)).isEqualTo(emptyOptionSet.getValue((Option) null)); - } - - @Test - public void parseEmptyThrowsNullPointerException() throws Exception { - assertThatThrownBy(() -> this.emptyOptionParser.parse("")) - .isInstanceOf(NullPointerException.class); - } - - @Test - public void setArgumentsShouldCreateCopy() throws Exception { - Argument argument = mock(Argument.class); - when(argument.isRequired()).thenReturn(true); - - LinkedList<Argument> arguments = new LinkedList<>(); - arguments.add(argument); - - this.emptyOptionParser.setArguments(arguments); - - assertThat(this.emptyOptionParser.getArguments()).isNotSameAs(arguments); - assertThat(this.emptyOptionParser.getArguments()).hasSize(1); - - arguments.clear(); - - assertThat(arguments).hasSize(0); - assertThat(this.emptyOptionParser.getArguments()).hasSize(1); - } - - @Test - public void setArgumentsShouldKeepRequiredBeforeOptional() throws Exception { - Argument requiredArgument1 = mock(Argument.class); - when(requiredArgument1.isRequired()).thenReturn(true); - Argument optionalArgument1 = mock(Argument.class); - when(optionalArgument1.isRequired()).thenReturn(false); - - LinkedList<Argument> arguments = new LinkedList<>(); - arguments.add(requiredArgument1); - arguments.add(optionalArgument1); - - this.emptyOptionParser.setArguments(arguments); - - LinkedList<Argument> argumentsReturned = this.emptyOptionParser.getArguments(); - - assertThat(argumentsReturned).hasSize(2); - assertThat(argumentsReturned.getFirst()).isSameAs(requiredArgument1); - assertThat(argumentsReturned.getLast()).isSameAs(optionalArgument1); - } - - @Test - public void setArgumentsShouldMoveRequiredBeforeOptional() throws Exception { - Argument requiredArgument1 = mock(Argument.class); - when(requiredArgument1.isRequired()).thenReturn(true); - Argument optionalArgument1 = mock(Argument.class); - when(optionalArgument1.isRequired()).thenReturn(false); - - LinkedList<Argument> arguments = new LinkedList<>(); - arguments.add(optionalArgument1); - arguments.add(requiredArgument1); - - this.emptyOptionParser.setArguments(arguments); - - LinkedList<Argument> argumentsReturned = this.emptyOptionParser.getArguments(); - - assertThat(argumentsReturned).hasSize(2); - assertThat(argumentsReturned.getFirst()).isSameAs(requiredArgument1); - assertThat(argumentsReturned.getLast()).isSameAs(optionalArgument1); - } - - @Test - public void setOptionsShouldKeepSameInstance() throws Exception { - Option option = mock(Option.class); - ArrayList aggregate = new ArrayList<String>(); - aggregate.add("option"); - when(option.getAggregate()).thenReturn(aggregate); - when(option.getHelp()).thenReturn("help text"); - - LinkedList<Option> options = new LinkedList<>(); - options.add(option); - - this.emptyOptionParser.setOptions(options); - - assertThat(this.emptyOptionParser.getOptions()).isSameAs(options); - assertThat(this.emptyOptionParser.getOptions()).hasSize(1); - - options.clear(); - - assertThat(options).hasSize(0); - assertThat(this.emptyOptionParser.getOptions()).hasSize(0); - } - - @Test - public void parseInputWithDefinedArgumentShouldWork() throws Exception { - LinkedList<Argument> arguments = new LinkedList<>(); - LinkedList<Option> options = new LinkedList<>(); - - arguments.add(this.requiredArgument); - - JoptOptionParser optionParser = new JoptOptionParser(); - optionParser.setArguments(arguments); - optionParser.setOptions(options); - - OptionSet optionSet = optionParser.parse("command1 argument1_value"); - assertThat(optionSet.areArgumentsPresent()).isTrue(); - assertThat(optionSet.hasArgument(this.requiredArgument)).isTrue(); - } - - @Test - public void parseInputWithOneArgumentShouldFindJustOneArgument() throws Exception { - LinkedList<Argument> arguments = new LinkedList<>(); - LinkedList<Option> options = new LinkedList<>(); - - arguments.add(this.requiredArgument); - - JoptOptionParser optionParser = new JoptOptionParser(); - optionParser.setArguments(arguments); - optionParser.setOptions(options); - - OptionSet optionSet = optionParser.parse("command1 argument1_value"); - assertThat(optionSet.areArgumentsPresent()).isTrue(); - assertThat(optionSet.hasArgument(this.requiredArgument)).isTrue(); - assertThat(optionSet.hasArgument(this.optionalArgument)).isFalse(); - } - - @Test - public void parseInputWithTwoArgumentsShouldFindTwoArguments() throws Exception { - LinkedList<Argument> arguments = new LinkedList<>(); - LinkedList<Option> options = new LinkedList<>(); - - arguments.add(this.requiredArgument); - arguments.add(this.optionalArgument); - - JoptOptionParser optionParser = new JoptOptionParser(); - optionParser.setArguments(arguments); - optionParser.setOptions(options); - - OptionSet optionSet = optionParser.parse("command1 argument1_value? argument2_value"); - assertThat(optionSet.areArgumentsPresent()).isTrue(); - assertThat(optionSet.hasArgument(this.requiredArgument)).isTrue(); - assertThat(optionSet.hasArgument(this.optionalArgument)).isTrue(); - } - - @Test - public void parseInputWithUndefinedArgumentShouldNotThrow() throws Exception { - LinkedList<Argument> arguments = new LinkedList<>(); - LinkedList<Option> options = new LinkedList<>(); - - arguments.add(this.requiredArgument); - - JoptOptionParser optionParser = new JoptOptionParser(); - optionParser.setArguments(arguments); - optionParser.setOptions(options); - - OptionSet optionSet = optionParser.parse("command1 argument1_value? argument2_value"); - assertThat(optionSet.getUserInput()).isEqualTo("command1 argument1_value? argument2_value"); - } - - @Test - public void parseInputShouldIgnoreUndefinedOption() throws Exception { - // one fix for GEODE-1598 has a side effect of preventing our detection of undefined options - OptionSet optionSet = - this.simpleOptionParser.parse("command1 argument1_value argument2_value --undefinedOption"); - assertThat(optionSet.areOptionsPresent()).isFalse(); - assertThat(optionSet.hasOption(this.requiredOption)).isFalse(); - assertThat(optionSet.hasOption(this.optionalOption)).isFalse(); - } - - @Test - public void parseInputWithOneOptionShouldFindOneOption() throws Exception { - OptionSet optionSet = this.simpleOptionParser.parse("command1 argument1_value --option1"); - assertThat(optionSet.areOptionsPresent()).isTrue(); - assertThat(optionSet.hasOption(this.requiredOption)).isTrue(); - assertThat(optionSet.hasOption(this.optionalOption)).isFalse(); - } - - @Test - public void parseInputWithTwoOptionsShouldFindTwoOptions() throws Exception { - OptionSet optionSet = - this.simpleOptionParser.parse("command1 argument1_value --option1 --option2"); - assertThat(optionSet.areOptionsPresent()).isTrue(); - assertThat(optionSet.hasOption(this.requiredOption)).isTrue(); - assertThat(optionSet.hasOption(this.optionalOption)).isTrue(); - } - - @Test - public void parseInputWithOptionWithValueShouldFindOption() throws Exception { - OptionSet optionSet = this.simpleOptionParser.parse("command1 argument1_value --option1=value"); - assertThat(optionSet.areOptionsPresent()).isTrue(); - assertThat(optionSet.hasOption(this.requiredOption)).isTrue(); - } - - @Test - public void parseInputWithOptionWithoutValueShouldFindOption() throws Exception { - OptionSet optionSet = this.simpleOptionParser.parse("command1 argument1_value --option1"); - assertThat(optionSet.areOptionsPresent()).isTrue(); - assertThat(optionSet.hasOption(this.requiredOption)).isTrue(); - } - - @Test - public void parseInputWithoutOptionShouldNotFindOptions() throws Exception { - LinkedList<Argument> arguments = new LinkedList<>(); - LinkedList<Option> options = new LinkedList<>(); - - arguments.add(this.requiredArgument); - - JoptOptionParser optionParser = new JoptOptionParser(); - optionParser.setArguments(arguments); - optionParser.setOptions(options); - - OptionSet optionSet = optionParser.parse("command1 argument1_value"); - assertThat(optionSet.areOptionsPresent()).isFalse(); - assertThat(optionSet.hasOption(this.requiredOption)).isFalse(); - } - - @Test - @Parameters(method = "exampleInputParameters") - public void parseInputWithExampleInputParametesr(String command, boolean expectException, - boolean hasArguments, boolean hasOptions) throws Exception { - if (expectException) { - assertThatThrownBy(() -> this.exampleOptionParser.parse(command)) - .isExactlyInstanceOf(CliCommandOptionMissingException.class); - return; - } - - OptionSet options = this.exampleOptionParser.parse(command); - assertThat(options).isNotNull(); - assertThat(options.areArgumentsPresent()).isEqualTo(hasArguments); - assertThat(options.areOptionsPresent()).isEqualTo(hasOptions); - } - - private static Object[] exampleInputParameters() { - return new Object[] { - // 0 - new Object[] {" ARGUMENT1_VALUE âoption1=somevalue", false, true, false}, - // 1 - new Object[] {" ARGUMENT1_VALUE? ARGUMENT2_VALUE -- ----------", false, true, false}, - // 2 - new Object[] {" --option1=value", false, false, true}, - // 3 - new Object[] { - " ARGUMENT1_VALUE? ARGUMENT2_VALUE --option1=option1value --option2", - false, true, true}, - // 4 - new Object[] { - " ARGUMENT1_VALUE? ARGUMENT2_VALUE --option1=option1value --option2=option2value --option3=option3value", - false, true, true}, - // 5 - new Object[] { - " --string=string1 --stringArray=1,2 --stringArray=3,4 --stringList=11,12,13 --integer=10 --stringArray=5 --stringList=14,15", - false, false, true}, - // 6 - new Object[] {" --stringArray=1,2 --stringArray='3,4'", false, false, true}, - // 7 - new Object[] { - " --string=\"1\" --colonArray=2:3:4 --stringArray=5,\"6,7\",8 --stringList=\"9,10,11,12\"", - false, false, true}, - // 8 - new Object[] {" --string=string1 --stringArray=1,2 --string=string2", false, false, true}, - // 9 - new Object[] {" this is just one argument?this is a second argument", false, true, false}}; - } - - private void defineSimpleOptionParser() { - LinkedList<Argument> arguments = new LinkedList<Argument>(); - LinkedList<Option> options = new LinkedList<Option>(); - - this.requiredArgument = mock(Argument.class); - when(this.requiredArgument.getArgumentName()).thenReturn("argument1"); - when(this.requiredArgument.getContext()).thenReturn("context for argument1"); - when(this.requiredArgument.getHelp()).thenReturn("help for argument1"); - when(this.requiredArgument.isRequired()).thenReturn(true); - arguments.add(this.requiredArgument); - - this.optionalArgument = mock(Argument.class); - when(this.optionalArgument.getArgumentName()).thenReturn("argument2"); - when(this.optionalArgument.getContext()).thenReturn("context for argument2"); - when(this.optionalArgument.getHelp()).thenReturn("help for argument2"); - when(this.optionalArgument.isRequired()).thenReturn(false); - when(this.optionalArgument.getUnspecifiedDefaultValue()) - .thenReturn("{unspecified default value for argument2}"); - when(this.optionalArgument.isSystemProvided()).thenReturn(false); - arguments.add(this.optionalArgument); - - this.requiredOption = mock(Option.class); - when(this.requiredOption.getLongOption()).thenReturn("--option1"); - List<String> aggregate = new ArrayList<>(); - aggregate.add("option1"); - when(this.requiredOption.getAggregate()).thenReturn(aggregate); - when(this.requiredOption.getLongOption()).thenReturn("option1"); - when(this.requiredOption.getHelp()).thenReturn("help for option1"); - when(this.requiredOption.getValueSeparator()).thenReturn("="); - when(this.requiredOption.isRequired()).thenReturn(true); - assertThat(this.requiredOption.getAggregate()).isNotEmpty(); - options.add(this.requiredOption); - - this.optionalOption = mock(Option.class); - when(this.optionalOption.getLongOption()).thenReturn("--option2"); - aggregate = new ArrayList<>(); - aggregate.add("option2"); - when(this.optionalOption.getAggregate()).thenReturn(aggregate); - when(this.optionalOption.getLongOption()).thenReturn("option2"); - when(this.optionalOption.getHelp()).thenReturn("help for option2"); - when(this.optionalOption.getValueSeparator()).thenReturn("="); - when(this.optionalOption.isRequired()).thenReturn(false); - assertThat(this.optionalOption.getAggregate()).isNotEmpty(); - options.add(this.optionalOption); - - this.simpleOptionParser = new JoptOptionParser(); - this.simpleOptionParser.setArguments(arguments); - this.simpleOptionParser.setOptions(options); - } - - private void defineExampleOptionParser() { - LinkedList<Argument> arguments = new LinkedList<Argument>(); - LinkedList<Option> options = new LinkedList<Option>(); - - Argument argument1 = mock(Argument.class); - when(argument1.getArgumentName()).thenReturn("argument1"); - when(argument1.getContext()).thenReturn("context for argument1"); - when(argument1.getHelp()).thenReturn("help for argument1"); - when(argument1.isRequired()).thenReturn(true); - arguments.add(argument1); - - Argument argument2 = mock(Argument.class); - when(argument2.getArgumentName()).thenReturn("argument2"); - when(argument2.getContext()).thenReturn("context for argument2"); - when(argument2.getHelp()).thenReturn("help for argument2"); - when(argument2.isRequired()).thenReturn(false); - when(argument2.getUnspecifiedDefaultValue()) - .thenReturn("{unspecified default value for argument2}"); - when(argument2.isSystemProvided()).thenReturn(false); - arguments.add(argument2); - - Argument argument3 = mock(Argument.class); - when(argument3.getArgumentName()).thenReturn("argument3"); - when(argument3.getContext()).thenReturn("context for argument3"); - when(argument3.getHelp()).thenReturn("help for argument3"); - when(argument3.isRequired()).thenReturn(false); - when(argument3.getUnspecifiedDefaultValue()) - .thenReturn("{unspecified default value for argument3}"); - when(argument2.isSystemProvided()).thenReturn(false); - arguments.add(argument3); - - Option option1 = mock(Option.class); - when(option1.getLongOption()).thenReturn("--option1"); - List<String> aggregate1 = new ArrayList<>(); - aggregate1.add("option1"); - when(option1.getAggregate()).thenReturn(aggregate1); - when(option1.getLongOption()).thenReturn("option1"); - when(option1.getHelp()).thenReturn("help for option1"); - when(option1.getValueSeparator()).thenReturn("="); - when(option1.isRequired()).thenReturn(false); - assertThat(option1.getAggregate()).isNotEmpty(); - options.add(option1); - - Option option2 = mock(Option.class); - when(option2.getLongOption()).thenReturn("--option2"); - List<String> aggregate2 = new ArrayList<>(); - aggregate2.add("option2"); - when(option2.getAggregate()).thenReturn(aggregate2); - when(option2.getLongOption()).thenReturn("option2"); - when(option2.getHelp()).thenReturn("help for option2"); - when(option2.getValueSeparator()).thenReturn("="); - when(option2.isRequired()).thenReturn(false); - assertThat(option2.getAggregate()).isNotEmpty(); - options.add(option2); - - Option option3 = mock(Option.class); - when(option3.getLongOption()).thenReturn("--option3"); - List<String> aggregate3 = new ArrayList<>(); - aggregate3.add("option3"); - when(option3.getAggregate()).thenReturn(aggregate3); - when(option3.getLongOption()).thenReturn("option3"); - when(option3.getHelp()).thenReturn("help for option3"); - when(option3.getValueSeparator()).thenReturn("="); - when(option3.isRequired()).thenReturn(false); - assertThat(option3.getAggregate()).isNotEmpty(); - options.add(option3); - - Option stringOption = mock(Option.class); - when(stringOption.getLongOption()).thenReturn("--string"); - List<String> aggregateStringOption = new ArrayList<>(); - aggregateStringOption.add("string"); - when(stringOption.getAggregate()).thenReturn(aggregateStringOption); - when(stringOption.getLongOption()).thenReturn("string"); - when(stringOption.getHelp()).thenReturn("help for string"); - when(stringOption.getValueSeparator()).thenReturn("="); - when(stringOption.isRequired()).thenReturn(false); - assertThat(stringOption.getAggregate()).isNotEmpty(); - options.add(stringOption); - - Option stringArrayOption = mock(Option.class); - when(stringArrayOption.getLongOption()).thenReturn("--stringArray"); - List<String> aggregateStringArrayOption = new ArrayList<>(); - aggregateStringArrayOption.add("stringArray"); - when(stringArrayOption.getAggregate()).thenReturn(aggregateStringArrayOption); - when(stringArrayOption.getLongOption()).thenReturn("stringArray"); - when(stringArrayOption.getHelp()).thenReturn("help for stringArray"); - when(stringArrayOption.getValueSeparator()).thenReturn("="); - when(stringArrayOption.isRequired()).thenReturn(false); - assertThat(stringArrayOption.getAggregate()).isNotEmpty(); - options.add(stringArrayOption); - - Option stringListOption = mock(Option.class); - when(stringListOption.getLongOption()).thenReturn("--stringList"); - List<String> aggregateStringListOption = new ArrayList<>(); - aggregateStringListOption.add("stringList"); - when(stringListOption.getAggregate()).thenReturn(aggregateStringListOption); - when(stringListOption.getLongOption()).thenReturn("stringList"); - when(stringListOption.getHelp()).thenReturn("help for stringList"); - when(stringListOption.getValueSeparator()).thenReturn("="); - when(stringListOption.isRequired()).thenReturn(false); - assertThat(stringListOption.getAggregate()).isNotEmpty(); - options.add(stringListOption); - - Option integerOption = mock(Option.class); - when(integerOption.getLongOption()).thenReturn("--integer"); - List<String> aggregateIntegerOption = new ArrayList<>(); - aggregateIntegerOption.add("integer"); - when(integerOption.getAggregate()).thenReturn(aggregateIntegerOption); - when(integerOption.getLongOption()).thenReturn("integer"); - when(integerOption.getHelp()).thenReturn("help for integer"); - when(integerOption.getValueSeparator()).thenReturn("="); - when(integerOption.isRequired()).thenReturn(false); - assertThat(integerOption.getAggregate()).isNotEmpty(); - options.add(integerOption); - - Option colonArrayOption = mock(Option.class); - when(colonArrayOption.getLongOption()).thenReturn("--colonArray"); - List<String> aggregateColonArrayOption = new ArrayList<>(); - aggregateColonArrayOption.add("colonArray"); - when(colonArrayOption.getAggregate()).thenReturn(aggregateColonArrayOption); - when(colonArrayOption.getLongOption()).thenReturn("colonArray"); - when(colonArrayOption.getHelp()).thenReturn("help for colonArray"); - when(colonArrayOption.getValueSeparator()).thenReturn("="); - when(colonArrayOption.isRequired()).thenReturn(false); - assertThat(colonArrayOption.getAggregate()).isNotEmpty(); - options.add(colonArrayOption); - - this.exampleOptionParser = new JoptOptionParser(); - this.exampleOptionParser.setArguments(arguments); - this.exampleOptionParser.setOptions(options); - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/809d64d7/geode-core/src/test/java/org/apache/geode/management/internal/cli/NewGfshParserJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/NewGfshParserJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/NewGfshParserJUnitTest.java new file mode 100644 index 0000000..d6d658b --- /dev/null +++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/NewGfshParserJUnitTest.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.geode.management.internal.cli; + +import static org.junit.Assert.assertEquals; + +import org.apache.geode.test.junit.categories.UnitTest; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import java.util.List; + +/** + * GfshParserJUnitTest - Includes tests to check the parsing and auto-completion capabilities of + * {@link GfshParser} + */ +@Category(UnitTest.class) +public class NewGfshParserJUnitTest { + @Test + public void testSplitUserInputDoubleQuotes() { + String str = "query --query=\"select * from /region\""; + List<String> tokens = GfshParser.splitUserInput(str); + assertEquals(3, tokens.size()); + assertEquals("query", tokens.get(0)); + assertEquals("--query", tokens.get(1)); + assertEquals("\"select * from /region\"", tokens.get(2)); + } + + @Test + public void testSplitUserInputSingleQuotes() { + String str = "query --query='select * from /region'"; + List<String> tokens = GfshParser.splitUserInput(str); + assertEquals(3, tokens.size()); + assertEquals("query", tokens.get(0)); + assertEquals("--query", tokens.get(1)); + assertEquals("'select * from /region'", tokens.get(2)); + } + + @Test + public void testSplitUserInputWithJ() { + String + str = + "start server --name=server1 --J=\"-Dgemfire.start-dev-rest-api=true\" --J='-Dgemfire.http-service-port=8080' --J='-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=30000'"; + List<String> tokens = GfshParser.splitUserInput(str); + assertEquals(10, tokens.size()); + assertEquals("\"-Dgemfire.start-dev-rest-api=true\"", tokens.get(5)); + assertEquals("'-Dgemfire.http-service-port=8080'", tokens.get(7)); + assertEquals("'-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=30000'", + tokens.get(9)); + } + + @Test + public void testSplitUserInputWithJNoQuotes() { + String + str = + "start server --name=server1 --J=-Dgemfire.start-dev-rest-api=true --J=-Dgemfire.http-service-port=8080"; + List<String> tokens = GfshParser.splitUserInput(str); + assertEquals(8, tokens.size()); + assertEquals("-Dgemfire.start-dev-rest-api=true", tokens.get(5)); + assertEquals("-Dgemfire.http-service-port=8080", tokens.get(7)); + } +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/809d64d7/geode-core/src/test/java/org/apache/geode/management/internal/cli/annotations/CliArgumentJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/annotations/CliArgumentJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/annotations/CliArgumentJUnitTest.java deleted file mode 100644 index 161f7c6..0000000 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/annotations/CliArgumentJUnitTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You 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.apache.geode.management.internal.cli.annotations; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import org.apache.geode.management.internal.cli.annotation.CliArgument; -import org.apache.geode.test.junit.categories.UnitTest; - -/** - * Includes tests for checking assignment of {@link CliArgument} - */ -@Category(UnitTest.class) -public class CliArgumentJUnitTest { - - private static final String ARGUMENT_NAME = "ARGUMENT_NAME"; - private static final String ARGUMENT_HELP = "ARGUMENT_HELP"; - private static final boolean ARGUMENT_MANDATORY = true; - private static final String ARGUMENT_CONTEXT = "ARGUMENT_CONTEXT"; - private static final boolean SYSTEM_PROVIDED = true; - private static final String ARGUMENT_UNSPECIFIED_DEFAULT_VALUE = - "ARGUMENT_UNSPECIFIED_DEFAULT_VALUE"; - private static final String MESSAGE_FOR_DEFAULT_ARGUMENT = "Testing for argument with defaults"; - private static final String MESSAGE_FOR_ARGUMENT = "Testing for argument without defaults"; - - /** - * Test for {@link CliArgument#name()} - */ - @Test - public void testName() throws Exception { - String name = ((CliArgument) (ArgumentTestingClass.class - .getMethod("defaultArgumentTestingMethod", String.class).getParameterAnnotations()[0][0])) - .name(); - assertNotNull(name); - assertEquals(MESSAGE_FOR_DEFAULT_ARGUMENT, name, ARGUMENT_NAME); - name = ((CliArgument) (ArgumentTestingClass.class - .getMethod("argumentTestingMethod", String.class).getParameterAnnotations()[0][0])).name(); - assertNotNull(name); - assertEquals(MESSAGE_FOR_ARGUMENT, name, ARGUMENT_NAME); - } - - /** - * Test for {@link CliArgument#help()} - */ - @Test - public void testHelp() throws Exception { - String help = ((CliArgument) (ArgumentTestingClass.class - .getMethod("defaultArgumentTestingMethod", String.class).getParameterAnnotations()[0][0])) - .help(); - assertNotNull(help); - assertEquals(MESSAGE_FOR_DEFAULT_ARGUMENT, help, ""); - help = ((CliArgument) (ArgumentTestingClass.class - .getMethod("argumentTestingMethod", String.class).getParameterAnnotations()[0][0])).help(); - assertNotNull(help); - assertEquals(MESSAGE_FOR_ARGUMENT, help, ARGUMENT_HELP); - } - - /** - * Test for {@link CliArgument#mandatory()} - */ - @Test - public void testMandatory() throws Exception { - boolean mandatory = ((CliArgument) (ArgumentTestingClass.class - .getMethod("defaultArgumentTestingMethod", String.class).getParameterAnnotations()[0][0])) - .mandatory(); - assertEquals(MESSAGE_FOR_DEFAULT_ARGUMENT, mandatory, false); - mandatory = - ((CliArgument) (ArgumentTestingClass.class.getMethod("argumentTestingMethod", String.class) - .getParameterAnnotations()[0][0])).mandatory(); - assertEquals(MESSAGE_FOR_ARGUMENT, mandatory, ARGUMENT_MANDATORY); - } - - /** - * Test for {@link CliArgument#argumentContext()} - */ - @Test - public void testArgumentContext() throws Exception { - String argumentContext = ((CliArgument) (ArgumentTestingClass.class - .getMethod("defaultArgumentTestingMethod", String.class).getParameterAnnotations()[0][0])) - .argumentContext(); - assertNotNull(argumentContext); - assertEquals(MESSAGE_FOR_DEFAULT_ARGUMENT, argumentContext, ""); - argumentContext = - ((CliArgument) (ArgumentTestingClass.class.getMethod("argumentTestingMethod", String.class) - .getParameterAnnotations()[0][0])).argumentContext(); - assertNotNull(argumentContext); - assertEquals(MESSAGE_FOR_ARGUMENT, argumentContext, ARGUMENT_CONTEXT); - } - - /** - * Test for {@link CliArgument#systemProvided()} - */ - @Test - public void testSystemProvided() throws Exception { - boolean systemProvided = ((CliArgument) (ArgumentTestingClass.class - .getMethod("defaultArgumentTestingMethod", String.class).getParameterAnnotations()[0][0])) - .systemProvided(); - assertEquals(MESSAGE_FOR_DEFAULT_ARGUMENT, systemProvided, false); - systemProvided = - ((CliArgument) (ArgumentTestingClass.class.getMethod("argumentTestingMethod", String.class) - .getParameterAnnotations()[0][0])).systemProvided(); - assertEquals(MESSAGE_FOR_ARGUMENT, systemProvided, SYSTEM_PROVIDED); - } - - /** - * Test for {@link CliArgument#unspecifiedDefaultValue()} - */ - @Test - public void testUnspecifiedDefaultValue() throws Exception { - String unspecifiedDefaultValue = ((CliArgument) (ArgumentTestingClass.class - .getMethod("defaultArgumentTestingMethod", String.class).getParameterAnnotations()[0][0])) - .unspecifiedDefaultValue(); - assertEquals(MESSAGE_FOR_DEFAULT_ARGUMENT, unspecifiedDefaultValue, "__NULL__"); - unspecifiedDefaultValue = - ((CliArgument) (ArgumentTestingClass.class.getMethod("argumentTestingMethod", String.class) - .getParameterAnnotations()[0][0])).unspecifiedDefaultValue(); - assertEquals(MESSAGE_FOR_ARGUMENT, unspecifiedDefaultValue, ARGUMENT_UNSPECIFIED_DEFAULT_VALUE); - } - - /** - * Class used by the tests - */ - private static class ArgumentTestingClass { - - @SuppressWarnings("unused") - public static Object defaultArgumentTestingMethod( - @CliArgument(name = ARGUMENT_NAME) String defaultArgument) { - return null; - } - - @SuppressWarnings("unused") - public static Object argumentTestingMethod( - @CliArgument(name = ARGUMENT_NAME, help = ARGUMENT_HELP, mandatory = ARGUMENT_MANDATORY, - argumentContext = ARGUMENT_CONTEXT, systemProvided = SYSTEM_PROVIDED, - unspecifiedDefaultValue = ARGUMENT_UNSPECIFIED_DEFAULT_VALUE) String argument) { - return null; - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/809d64d7/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CliCommandTestBase.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CliCommandTestBase.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CliCommandTestBase.java index 68cb150..41f5ea9 100644 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CliCommandTestBase.java +++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CliCommandTestBase.java @@ -14,22 +14,17 @@ */ package org.apache.geode.management.internal.cli.commands; -import static org.apache.geode.distributed.ConfigurationProperties.*; -import static org.apache.geode.test.dunit.Assert.*; -import static org.apache.geode.test.dunit.LogWriterUtils.*; - -import java.io.IOException; -import java.io.PrintStream; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.geode.security.templates.SampleSecurityManager; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT; +import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER; +import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_BIND_ADDRESS; +import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT; +import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_START; +import static org.apache.geode.distributed.ConfigurationProperties.NAME; +import static org.apache.geode.test.dunit.Assert.assertEquals; +import static org.apache.geode.test.dunit.Assert.assertFalse; +import static org.apache.geode.test.dunit.Assert.assertNotNull; +import static org.apache.geode.test.dunit.Assert.assertTrue; +import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter; import org.apache.geode.cache.Cache; import org.apache.geode.internal.AvailablePortHelper; @@ -37,14 +32,27 @@ import org.apache.geode.management.ManagementService; import org.apache.geode.management.internal.cli.CommandManager; import org.apache.geode.management.internal.cli.HeadlessGfsh; import org.apache.geode.management.internal.cli.i18n.CliStrings; -import org.apache.geode.management.internal.cli.parser.CommandTarget; import org.apache.geode.management.internal.cli.result.CommandResult; import org.apache.geode.management.internal.cli.shell.Gfsh; import org.apache.geode.management.internal.cli.util.CommandStringBuilder; +import org.apache.geode.security.templates.SampleSecurityManager; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.IgnoredException; import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase; import org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import org.springframework.shell.core.CommandMarker; + +import java.io.IOException; +import java.io.PrintStream; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Base class for all the CLI/gfsh command dunit tests. @@ -52,24 +60,45 @@ import org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties; public abstract class CliCommandTestBase extends JUnit4CacheTestCase { public static final String USE_HTTP_SYSTEM_PROPERTY = "useHTTP"; - - private boolean useHttpOnConnect = Boolean.getBoolean(USE_HTTP_SYSTEM_PROPERTY); - - private ManagementService managementService; - - private transient HeadlessGfsh shell; - + @Rule + public transient DistributedRestoreSystemProperties restoreSystemProperties = + new DistributedRestoreSystemProperties(); + @Rule + public transient TemporaryFolder temporaryFolder = new TemporaryFolder(); protected transient int httpPort; protected transient int jmxPort; protected transient String jmxHost; protected transient String gfshDir; + private boolean useHttpOnConnect = Boolean.getBoolean(USE_HTTP_SYSTEM_PROPERTY); + private ManagementService managementService; + private transient HeadlessGfsh shell; - @Rule - public transient DistributedRestoreSystemProperties restoreSystemProperties = - new DistributedRestoreSystemProperties(); + public static boolean checkIfCommandsAreLoadedOrNot() { + CommandManager manager; + try { + manager = CommandManager.getInstance(); + List<CommandMarker> commands = manager.getCommandMarkers(); + return commands.size() >= 1; + } catch (ClassNotFoundException | IOException e) { + throw new RuntimeException("Could not load commands", e); + } + } - @Rule - public transient TemporaryFolder temporaryFolder = new TemporaryFolder(); + protected static String commandResultToString(final CommandResult commandResult) { + assertNotNull(commandResult); + + commandResult.resetToFirstLine(); + + StringBuilder buffer = new StringBuilder(commandResult.getHeader()); + + while (commandResult.hasNextLine()) { + buffer.append(commandResult.nextLine()); + } + + buffer.append(commandResult.getFooter()); + + return buffer.toString(); + } @Override public final void postSetUp() throws Exception { @@ -195,20 +224,6 @@ public abstract class CliCommandTestBase extends JUnit4CacheTestCase { assertTrue(checkIfCommandsAreLoadedOrNot()); } - public static boolean checkIfCommandsAreLoadedOrNot() { - CommandManager manager; - try { - manager = CommandManager.getInstance(); - Map<String, CommandTarget> commands = manager.getCommands(); - if (commands.size() < 1) { - return false; - } - return true; - } catch (ClassNotFoundException | IOException e) { - throw new RuntimeException("Could not load commands", e); - } - } - /** * Stop the default management service. */ @@ -387,22 +402,6 @@ public abstract class CliCommandTestBase extends JUnit4CacheTestCase { printStream.print(commandResultToString(commandResult)); } - protected static String commandResultToString(final CommandResult commandResult) { - assertNotNull(commandResult); - - commandResult.resetToFirstLine(); - - StringBuilder buffer = new StringBuilder(commandResult.getHeader()); - - while (commandResult.hasNextLine()) { - buffer.append(commandResult.nextLine()); - } - - buffer.append(commandResult.getFooter()); - - return buffer.toString(); - } - /** * Utility method for finding the CommandResult object in the Map of CommandOutput objects. *
