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.assertThrows;
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 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 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 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 void testLackOfError() throws Exception {
72 final String[] args = { "-k", "-a", "Caesar" };
73 final MissingArgumentException e = assertThrows(MissingArgumentException.class, () -> parser.parse(options, args));
74 assertEquals("k", e.getOption().getOpt(), "option missing an argument");
75 }
76
77 @Test
78 void testMistakenArgument() throws Exception {
79 String[] args = {"-a", "Caesar", "-k", "A"};
80 CommandLine line = parser.parse(options, args);
81 args = new String[] {"-a", "Caesar", "-k", "a"};
82 line = parser.parse(options, args);
83 assertEquals("Caesar", line.getOptionValue("a"));
84 assertEquals("a", line.getOptionValue("k"));
85 }
86
87 }