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