2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
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.
10 package eu.svjatoslav.commons.commandline.parameterparser;
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;
18 import java.io.FileWriter;
19 import java.io.IOException;
21 import static org.junit.Assert.*;
23 public class ParserTest {
29 parser = new Parser();
33 public void testParse() throws IOException {
35 // define allowed parameters
36 final StringParameter helpParameter = parser.add(new StringParameter("Show help screen")
37 .addAliases("--help", "-h").setMandatory());
39 final StringParameter compileParameter = parser.add(new StringParameter("Compile code"))
40 .addAliases("--compile", "-c");
42 FileParameter fileParameter = parser.add(new FileParameter("Input file")
43 .addAliases("-i").mustExist());
45 createTemporaryFile();
47 // check help generation
51 parser.parse(new String[]{"--help", "section", "-i", "/tmp/file with spaces"});
53 // --help was in the arguments
54 assertTrue(helpParameter.isSpecified());
56 // compile was not present
57 assertFalse(compileParameter.isSpecified());
59 // validate that help argument was "section"
60 assertEquals("section", helpParameter.getValue());
62 assertTrue(fileParameter.isSpecified());
63 assertEquals("/tmp/file with spaces", fileParameter.getValue().getAbsolutePath());
67 private void createTemporaryFile() throws IOException {
68 File fileWithSpaces = new File("/tmp/file with spaces");
69 FileWriter writer = new FileWriter(fileWithSpaces);