1 package org.djutils.cli;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.fail;
5
6 import org.junit.Test;
7
8 import picocli.CommandLine;
9 import picocli.CommandLine.Command;
10 import picocli.CommandLine.Option;
11
12
13
14
15
16
17
18
19
20 public class TestCLICommandLine
21 {
22
23 @Command(description = "Test program for CLI", name = "Program", mixinStandardHelpOptions = true, version = "1.0")
24 public static class Options implements Checkable
25 {
26
27 @Option(names = {"-p", "--port"}, description = "Internet port to use", defaultValue = "80")
28 private int port;
29
30
31 public int getPort()
32 {
33 return this.port;
34 }
35
36
37 @Override
38 public void check() throws Exception
39 {
40 if (this.port <= 0 || this.port > 65535)
41 {
42 throw new Exception("Port should be between 1 and 65535");
43 }
44 }
45 }
46
47
48
49
50
51
52
53
54 @Test
55 public void testCli() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, CliException
56 {
57
58 System.setSecurityManager(new ExitHelper.NoExitSecurityManager());
59
60
61 String[] args = new String[] {"-p", "2400"};
62 Options options = new Options();
63 CommandLine cmd = new CommandLine(options);
64 CliUtil.execute(cmd, args);
65 assertEquals(2400, options.getPort());
66 assertEquals("1.0", options.getClass().getAnnotation(Command.class).version()[0]);
67 assertEquals("Program", options.getClass().getAnnotation(Command.class).name());
68 assertEquals("Test program for CLI", options.getClass().getAnnotation(Command.class).description()[0]);
69
70
71 args = new String[] {"-p", "240000"};
72 options = new Options();
73 cmd = new CommandLine(options);
74 try
75 {
76 CliUtil.execute(cmd, args);
77 fail("check() is not called: the program should exit with an error message when a wrong port is provided");
78 }
79 catch (ExitHelper.ExitException e)
80 {
81
82 }
83
84 System.setSecurityManager(null);
85 }
86 }