Updated copyright notice
[svjatoslav_commons.git] / src / test / java / eu / svjatoslav / commons / commandline / parameterparser / ParserTest.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2018, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.commons.commandline.parameterparser;
11
12 import eu.svjatoslav.commons.commandline.parameterparser.parameter.FileParameter;
13 import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameter;
14 import org.junit.Before;
15 import org.junit.Test;
16
17 import java.io.File;
18 import java.io.FileWriter;
19 import java.io.IOException;
20
21 import static org.junit.Assert.*;
22
23 public class ParserTest {
24
25     Parser parser;
26
27     @Before
28     public void setUp() {
29         parser = new Parser();
30     }
31
32     @Test
33     public void testParse() throws IOException {
34
35         // define allowed parameters
36         final StringParameter helpParameter = parser.add(new StringParameter("Show help screen")
37                 .addAliases("--help", "-h").setMandatory());
38
39         final StringParameter compileParameter = parser.add(new StringParameter("Compile code"))
40                 .addAliases("--compile", "-c");
41
42         FileParameter fileParameter = parser.add(new FileParameter("Input file")
43                 .addAliases("-i").mustExist());
44
45         createTemporaryFile();
46
47         // check help generation
48         parser.showHelp();
49
50         // parse arguments
51         parser.parse(new String[]{"--help", "section", "-i", "/tmp/file with spaces"});
52
53         // --help was in the arguments
54         assertTrue(helpParameter.isSpecified());
55
56         // compile was not present
57         assertFalse(compileParameter.isSpecified());
58
59         // validate that help argument was "section"
60         assertEquals("section", helpParameter.getValue());
61
62         assertTrue(fileParameter.isSpecified());
63         assertEquals("/tmp/file with spaces", fileParameter.getValue().getAbsolutePath());
64
65     }
66
67     private void createTemporaryFile() throws IOException {
68         File fileWithSpaces = new File("/tmp/file with spaces");
69         FileWriter writer = new FileWriter(fileWithSpaces);
70         writer.write("test");
71         writer.close();
72     }
73 }