You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by eb...@apache.org on 2008/07/25 18:23:43 UTC

svn commit: r679851 - in /commons/proper/cli/branches/cli-1.x/src: java/org/apache/commons/cli/PatternOptionBuilder.java java/org/apache/commons/cli/TypeHandler.java test/org/apache/commons/cli/PatternOptionBuilderTest.java

Author: ebourg
Date: Fri Jul 25 09:23:38 2008
New Revision: 679851

URL: http://svn.apache.org/viewvc?rev=679851&view=rev
Log:
Improved the test coverage of TypeHandler and PatternOptionBuilder

Modified:
    commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/PatternOptionBuilder.java
    commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/TypeHandler.java
    commons/proper/cli/branches/cli-1.x/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java

Modified: commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/PatternOptionBuilder.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/PatternOptionBuilder.java?rev=679851&r1=679850&r2=679851&view=diff
==============================================================================
--- commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/PatternOptionBuilder.java (original)
+++ commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/PatternOptionBuilder.java Fri Jul 25 09:23:38 2008
@@ -41,8 +41,9 @@
  *
  * <p>
  * For example, the following allows command line flags of '-v -p string-value -f /dir/file'.
+ * The exclamation mark precede a mandatory option.
  * </p>
- * <code>Options options = PatternOptionBuilder.parsePattern("vp:f/");</code>
+ * <code>Options options = PatternOptionBuilder.parsePattern("vp:!f/");</code>
  *
  * <p>
  * TODO These need to break out to OptionType and also 
@@ -86,93 +87,77 @@
     public static final Class URL_VALUE = URL.class;
 
     /**
-     * <p>Retrieve the class that <code>ch</code> represents.</p>
+     * Retrieve the class that <code>ch</code> represents.
      *
      * @param ch the specified character
      * @return The class that <code>ch</code> represents
      */
     public static Object getValueClass(char ch)
     {
-        if (ch == '@')
+        switch (ch)
         {
-            return PatternOptionBuilder.OBJECT_VALUE;
-        }
-        else if (ch == ':')
-        {
-            return PatternOptionBuilder.STRING_VALUE;
-        }
-        else if (ch == '%')
-        {
-            return PatternOptionBuilder.NUMBER_VALUE;
-        }
-        else if (ch == '+')
-        {
-            return PatternOptionBuilder.CLASS_VALUE;
-        }
-        else if (ch == '#')
-        {
-            return PatternOptionBuilder.DATE_VALUE;
-        }
-        else if (ch == '<')
-        {
-            return PatternOptionBuilder.EXISTING_FILE_VALUE;
-        }
-        else if (ch == '>')
-        {
-            return PatternOptionBuilder.FILE_VALUE;
-        }
-        else if (ch == '*')
-        {
-            return PatternOptionBuilder.FILES_VALUE;
-        }
-        else if (ch == '/')
-        {
-            return PatternOptionBuilder.URL_VALUE;
+            case '@':
+                return PatternOptionBuilder.OBJECT_VALUE;
+            case ':':
+                return PatternOptionBuilder.STRING_VALUE;
+            case '%':
+                return PatternOptionBuilder.NUMBER_VALUE;
+            case '+':
+                return PatternOptionBuilder.CLASS_VALUE;
+            case '#':
+                return PatternOptionBuilder.DATE_VALUE;
+            case '<':
+                return PatternOptionBuilder.EXISTING_FILE_VALUE;
+            case '>':
+                return PatternOptionBuilder.FILE_VALUE;
+            case '*':
+                return PatternOptionBuilder.FILES_VALUE;
+            case '/':
+                return PatternOptionBuilder.URL_VALUE;
         }
 
         return null;
     }
 
     /**
-     * <p>Returns whether <code>ch</code> is a value code, i.e.
-     * whether it represents a class in a pattern.</p>
+     * Returns whether <code>ch</code> is a value code, i.e.
+     * whether it represents a class in a pattern.
      * 
      * @param ch the specified character
      * @return true if <code>ch</code> is a value code, otherwise false.
      */
     public static boolean isValueCode(char ch)
     {
-        if ((ch != '@') && (ch != ':') && (ch != '%') && (ch != '+')
-            && (ch != '#') && (ch != '<') && (ch != '>') && (ch != '*')
-            && (ch != '/') && (ch != '!'))
-        {
-            return false;
-        }
-
-        return true;
+        return ch == '@'
+                || ch == ':'
+                || ch == '%'
+                || ch == '+'
+                || ch == '#'
+                || ch == '<'
+                || ch == '>'
+                || ch == '*'
+                || ch == '/'
+                || ch == '!';
     }
 
     /**
-     * <p>Returns the {@link Options} instance represented by 
-     * <code>pattern</code>.</p>
+     * Returns the {@link Options} instance represented by 
+     * <code>pattern</code>.
      *
      * @param pattern the pattern string
      * @return The {@link Options} instance
      */
     public static Options parsePattern(String pattern)
     {
-        int sz = pattern.length();
-
         char opt = ' ';
-        char ch = ' ';
         boolean required = false;
         Object type = null;
 
         Options options = new Options();
 
-        for (int i = 0; i < sz; i++)
+        for (int i = 0; i < pattern.length(); i++)
         {
-            ch = pattern.charAt(i);
+            char ch = pattern.charAt(i);
 
             // a value code comes after an option and specifies 
             // details about it

Modified: commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/TypeHandler.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/TypeHandler.java?rev=679851&r1=679850&r2=679851&view=diff
==============================================================================
--- commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/TypeHandler.java (original)
+++ commons/proper/cli/branches/cli-1.x/src/java/org/apache/commons/cli/TypeHandler.java Fri Jul 25 09:23:38 2008
@@ -35,8 +35,8 @@
 public class TypeHandler {
 
     /**
-     * <p>Returns the <code>Object</code> of type <code>obj</code>
-     * with the value of <code>str</code>.</p>
+     * Returns the <code>Object</code> of type <code>obj</code>
+     * with the value of <code>str</code>.
      *
      * @param str the command line value
      * @param obj the type of argument
@@ -49,8 +49,8 @@
     }
 
     /**
-     * <p>Returns the <code>Object</code> of type <code>clazz</code>
-     * with the value of <code>str</code>.</p>
+     * Returns the <code>Object</code> of type <code>clazz</code>
+     * with the value of <code>str</code>.
      *
      * @param str the command line value
      * @param clazz the type of argument
@@ -102,7 +102,7 @@
     }
 
     /**
-      * <p>Create an Object from the classname and empty constructor.</p>
+      * Create an Object from the classname and empty constructor.
       *
       * @param str the argument value
       * @return the initialised object, or null if it couldn't create 
@@ -118,7 +118,7 @@
         }
         catch (ClassNotFoundException cnfe)
         {
-            System.err.println("Unable to find: " + str);
+            System.err.println("Unable to find the class: " + str);
 
             return null;
         }
@@ -129,27 +129,17 @@
         {
             instance = cl.newInstance();
         }
-        catch (InstantiationException cnfe)
+        catch (Exception e)
         {
-            System.err.println("InstantiationException; Unable to create: "
-                               + str);
-
-            return null;
-        }
-        catch (IllegalAccessException cnfe)
-        {
-            System.err.println("IllegalAccessException; Unable to create: "
-                               + str);
-
-            return null;
+            System.err.println(e.getClass().getName() + "; Unable to create an instance of: " + str);
         }
 
         return instance;
     }
 
     /**
-     * <p>Create a number from a String. If a . is present, it creates a 
-     *    Double, otherwise a Long. </p>
+     * Create a number from a String. If a . is present, it creates a 
+     * Double, otherwise a Long.
      *
      * @param str the value
      * @return the number represented by <code>str</code>, if <code>str</code>
@@ -159,16 +149,13 @@
     {
         try
         {
-            if( str != null )
+            if( str.indexOf('.') != -1 )
+            {
+                return Double.valueOf(str);
+            }
+            else
             {
-                if( str.indexOf('.') != -1 )
-                {
-                    return Double.valueOf(str);
-                }
-                else
-                {
-                    return Long.valueOf(str);
-                }
+                return Long.valueOf(str);
             }
         }
         catch (NumberFormatException nfe)
@@ -180,7 +167,7 @@
     }
 
     /**
-     * <p>Returns the class whose name is <code>str</code>.</p>
+     * Returns the class whose name is <code>str</code>.
      *
      * @param str the class name
      * @return The class if it is found, otherwise return null
@@ -200,7 +187,7 @@
     }
 
     /**
-     * <p>Returns the date represented by <code>str</code>.</p>
+     * Returns the date represented by <code>str</code>.
      *
      * @param str the date string
      * @return The date if <code>str</code> is a valid date string,
@@ -212,7 +199,7 @@
     }
 
     /**
-     * <p>Returns the URL represented by <code>str</code>.</p>
+     * Returns the URL represented by <code>str</code>.
      *
      * @param str the URL string
      * @return The URL is <code>str</code> is well-formed, otherwise
@@ -224,16 +211,16 @@
         {
             return new URL(str);
         }
-        catch (MalformedURLException mue)
+        catch (MalformedURLException e)
         {
-            System.err.println("Unable to parse: " + str);
+            System.err.println("Unable to parse the URL: " + str);
 
             return null;
         }
     }
 
     /**
-     * <p>Returns the File represented by <code>str</code>.</p>
+     * Returns the File represented by <code>str</code>.
      *
      * @param str the File location
      * @return The file represented by <code>str</code>.
@@ -244,7 +231,7 @@
     }
 
     /**
-     * <p>Returns the File[] represented by <code>str</code>.</p>
+     * Returns the File[] represented by <code>str</code>.
      *
      * @param str the paths to the files
      * @return The File[] represented by <code>str</code>.

Modified: commons/proper/cli/branches/cli-1.x/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/branches/cli-1.x/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java?rev=679851&r1=679850&r2=679851&view=diff
==============================================================================
--- commons/proper/cli/branches/cli-1.x/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java (original)
+++ commons/proper/cli/branches/cli-1.x/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java Fri Jul 25 09:23:38 2008
@@ -28,40 +28,135 @@
  * Test case for the PatternOptionBuilder class 
  *
  * @author Henri Yandell
- **/
+ * @version $Revision$, $Date$
+ */
 public class PatternOptionBuilderTest extends TestCase
 {
-   public void testSimplePattern() throws Exception
-   {
-       Options options = PatternOptionBuilder.parsePattern("a:b@cde>f+n%t/");
-       String[] args = new String[] { "-c", "-a", "foo", "-b", "java.util.Vector", "-e", "build.xml", "-f", "java.util.Calendar", "-n", "4.5", "-t", "http://jakarta.apache.org/" };
-
-       CommandLineParser parser = new PosixParser();
-       CommandLine line = parser.parse(options,args);
-
-       assertEquals("flag a", "foo", line.getOptionValue("a"));
-       assertEquals("string flag a", "foo", line.getOptionObject("a"));
-       assertEquals("object flag b", new Vector(), line.getOptionObject("b"));
-       assertTrue("boolean true flag c", line.hasOption("c"));
-       assertFalse("boolean false flag d", line.hasOption("d"));
-       assertEquals("file flag e", new File("build.xml"), line.getOptionObject("e"));
-       assertEquals("class flag f", Calendar.class, line.getOptionObject("f"));
-       assertEquals("number flag n", new Double(4.5), line.getOptionObject("n"));
-       assertEquals("url flag t", new URL("http://jakarta.apache.org/"), line.getOptionObject("t"));
-
-       // tests the char methods of CommandLine that delegate to the String methods
-       assertEquals("flag a", "foo", line.getOptionValue('a'));
-       assertEquals("string flag a", "foo", line.getOptionObject('a'));
-       assertEquals("object flag b", new Vector(), line.getOptionObject('b'));
-       assertTrue("boolean true flag c", line.hasOption('c'));
-       assertFalse("boolean false flag d", line.hasOption('d'));
-       assertEquals("file flag e", new File("build.xml"), line.getOptionObject('e'));
-       assertEquals("class flag f", Calendar.class, line.getOptionObject('f'));
-       assertEquals("number flag n", new Double(4.5), line.getOptionObject('n'));
-       assertEquals("url flag t", new URL("http://jakarta.apache.org/"), line.getOptionObject('t'));
-
-       /// DATES NOT SUPPORTED YET.
-       //      assertEquals("number flag t", new Date(1023400137276L), line.getOptionObject('z'));
-       //     input is:  "Thu Jun 06 17:48:57 EDT 2002"
-   }
+    public void testSimplePattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("a:b@cde>f+n%t/");
+        String[] args = new String[]{"-c", "-a", "foo", "-b", "java.util.Vector", "-e", "build.xml", "-f", "java.util.Calendar", "-n", "4.5", "-t", "http://jakarta.apache.org/"};
+
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, args);
+
+        assertEquals("flag a", "foo", line.getOptionValue("a"));
+        assertEquals("string flag a", "foo", line.getOptionObject("a"));
+        assertEquals("object flag b", new Vector(), line.getOptionObject("b"));
+        assertTrue("boolean true flag c", line.hasOption("c"));
+        assertFalse("boolean false flag d", line.hasOption("d"));
+        assertEquals("file flag e", new File("build.xml"), line.getOptionObject("e"));
+        assertEquals("class flag f", Calendar.class, line.getOptionObject("f"));
+        assertEquals("number flag n", new Double(4.5), line.getOptionObject("n"));
+        assertEquals("url flag t", new URL("http://jakarta.apache.org/"), line.getOptionObject("t"));
+
+        // tests the char methods of CommandLine that delegate to the String methods
+        assertEquals("flag a", "foo", line.getOptionValue('a'));
+        assertEquals("string flag a", "foo", line.getOptionObject('a'));
+        assertEquals("object flag b", new Vector(), line.getOptionObject('b'));
+        assertTrue("boolean true flag c", line.hasOption('c'));
+        assertFalse("boolean false flag d", line.hasOption('d'));
+        assertEquals("file flag e", new File("build.xml"), line.getOptionObject('e'));
+        assertEquals("class flag f", Calendar.class, line.getOptionObject('f'));
+        assertEquals("number flag n", new Double(4.5), line.getOptionObject('n'));
+        assertEquals("url flag t", new URL("http://jakarta.apache.org/"), line.getOptionObject('t'));
+
+        /// DATES NOT SUPPORTED YET.
+        //      assertEquals("number flag t", new Date(1023400137276L), line.getOptionObject('z'));
+        //     input is:  "Thu Jun 06 17:48:57 EDT 2002"
+    }
+
+    public void testEmptyPattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("");
+        assertTrue(options.getOptions().isEmpty());
+    }
+
+    public void testUntypedPattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("abc");
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, new String[] { "-abc" });
+
+        assertTrue(line.hasOption('a'));
+        assertNull("value a", line.getOptionObject('a'));
+        assertTrue(line.hasOption('b'));
+        assertNull("value b", line.getOptionObject('b'));
+        assertTrue(line.hasOption('c'));
+        assertNull("value c", line.getOptionObject('c'));
+    }
+
+    public void testNumberPattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("n%d%x%");
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, new String[] { "-n", "1", "-d", "2.1", "-x", "3,5" });
+
+        assertEquals("n object class", Long.class, line.getOptionObject("n").getClass());
+        assertEquals("n value", new Long(1), line.getOptionObject("n"));
+
+        assertEquals("d object class", Double.class, line.getOptionObject("d").getClass());
+        assertEquals("d value", new Double(2.1), line.getOptionObject("d"));
+
+        assertNull("x object", line.getOptionObject("x"));
+    }
+
+    public void testClassPattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("c+d+");
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, new String[] { "-c", "java.util.Calendar", "-d", "System.DateTime" });
+
+        assertEquals("c value", Calendar.class, line.getOptionObject("c"));
+        assertNull("d value", line.getOptionObject("d"));
+    }
+
+    public void testObjectPattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("o@i@n@");
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, new String[] { "-o", "java.lang.String", "-i", "java.util.Calendar", "-n", "System.DateTime" });
+
+        assertEquals("o value", "", line.getOptionObject("o"));
+        assertNull("i value", line.getOptionObject("i"));
+        assertNull("n value", line.getOptionObject("n"));
+    }
+
+    public void testURLPattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("u/v/");
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, new String[] { "-u", "http://commons.apache.org", "-v", "foo://commons.apache.org" });
+
+        assertEquals("u value", new URL("http://commons.apache.org"), line.getOptionObject("u"));
+        assertNull("v value", line.getOptionObject("v"));
+    }
+
+    public void testExistingFilePattern() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("f<");
+        CommandLineParser parser = new PosixParser();
+        CommandLine line = parser.parse(options, new String[] { "-f", "test.properties" });
+
+        assertEquals("f value", new File("test.properties"), line.getOptionObject("f"));
+
+        // todo test if an error is returned if the file doesn't exists (when it's implemented)
+    }
+
+    public void testRequiredOption() throws Exception
+    {
+        Options options = PatternOptionBuilder.parsePattern("!n%m%");
+        CommandLineParser parser = new PosixParser();
+
+        try
+        {
+            parser.parse(options, new String[]{""});
+            fail("MissingOptionException wasn't thrown");
+        }
+        catch (MissingOptionException e)
+        {
+            assertEquals(1, e.getMissingOptions().size());
+            assertTrue(e.getMissingOptions().contains("n"));
+        }
+    }
 }