1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.cli.bug;
18
19 import junit.framework.TestCase;
20
21 import org.apache.commons.cli.*;
22
23 public class BugCLI71Test extends TestCase {
24
25 private Options options;
26 private CommandLineParser parser;
27
28 public void setUp() {
29 options = new Options();
30
31 Option algorithm = new Option("a" , "algo", true, "the algorithm which it to perform executing");
32 algorithm.setArgName("algorithm name");
33 options.addOption(algorithm);
34
35 Option key = new Option("k" , "key", true, "the key the setted algorithm uses to process");
36 algorithm.setArgName("value");
37 options.addOption(key);
38
39 parser = new PosixParser();
40 }
41
42 public void testBasic() throws Exception {
43 String[] args = new String[] { "-a", "Caesar", "-k", "A" };
44 CommandLine line = parser.parse( options, args);
45 assertEquals( "Caesar", line.getOptionValue("a") );
46 assertEquals( "A", line.getOptionValue("k") );
47 }
48
49 public void testMistakenArgument() throws Exception {
50 String[] args = new String[] { "-a", "Caesar", "-k", "A" };
51 CommandLine line = parser.parse( options, args);
52 args = new String[] { "-a", "Caesar", "-k", "a" };
53 line = parser.parse( options, args);
54 assertEquals( "Caesar", line.getOptionValue("a") );
55 assertEquals( "a", line.getOptionValue("k") );
56 }
57
58 public void testLackOfError() throws Exception {
59 String[] args = new String[] { "-k", "-a", "Caesar" };
60 try {
61 CommandLine line = parser.parse( options, args);
62 fail("MissingArgumentException expected");
63 } catch(MissingArgumentException mae) {
64
65 }
66 }
67
68 public void testGetsDefaultIfOptional() throws Exception {
69 String[] args = new String[] { "-k", "-a", "Caesar" };
70 options.getOption("k").setOptionalArg(true);
71 CommandLine line = parser.parse( options, args);
72
73 assertEquals( "Caesar", line.getOptionValue("a") );
74 assertEquals( "a", line.getOptionValue("k", "a") );
75 }
76
77 }