cbeust/jcommander — Issue #100: JCommander.parseWithoutValidation throws ParameterException
Author: lefou
Created: 2012-01-22 13:51:50+00:00
State: open

First a question: Is it correct, that parsing a commandline with parseWithoutValidation should NOT throw a ParameterException? If the answer is yes, than I found a bug.

My use case: an application that uses command-style interface. If no command is given, then a default command should be assumed. Because JCommander does not support default-commands, I first parse the commandline without validation and prepend my default command if the parser could not parse any command. Unfortunatelly, even when calling parseWithoutValidation method on JCommander class, I get a MissingCommandException. Of course, I could surround it with try-catch, but this might not be the intended behavior in the first place.

See my test case below.

```java
package de.tototec.bughunt

import com.beust.jcommander._
import org.testng.annotations.{ DataProvider, Test }
import org.testng.Assert._

class CmdTest {

@Parameters(commandNames = Array("--cmd-one"))
class CmdOne

@Parameters(commandNames = Array("--cmd-two"))
class CmdTwo {
@Parameter
var params = new java.util.LinkedList[String]
}

def parseArgs(withDefault: Boolean, args: Array[String]): String = {
val cmds = Array(new CmdOne(), new CmdTwo())
val jc = new JCommander()
cmds.foreach(jc.addCommand(_))
if (withDefault) {
// First check if an command was given, when not prepend default command (--cmd-two")
jc.parseWithoutValidation(args: _*)
if (jc.getParsedCommand == null) {
jc.parse((Array("--cmd-two") ++ args): _*)
}
} else {
jc.parse(args: _*)
}
jc.getParsedCommand
}

@DataProvider
def testData = Array(
Array("--cmd-one", false, Array("--cmd-one")),
Array("--cmd-two", false, Array("--cmd-two")),
Array("--cmd-two", false, Array("--cmd-two", "param1", "param2")),
// This is the relevant test case to test default commands
Array("--cmd-two", true, Array("param1", "param2"))
)

@Test(dataProvider = "testData")
def testArgsWithoutDefaultCmd(expected: String, requireDefault: Boolean, args: Array[String]) {
if (!requireDefault) {
assertEquals(parseArgs(false, args), expected)
}
}

@Test(dataProvider = "testData", expectedExceptions = Array(classOf[MissingCommandException]))
def testArgsWithoutDefaultCmdFail(expected: String, requireDefault: Boolean, args: Array[String]) {
if (requireDefault) {
parseArgs(false, args)
} else {
throw new MissingCommandException("irrelevant test case")
}
}

@Test(dataProvider = "testData")
def testArgsWithDefaultCmd(expected: String, requireDefault: Boolean, args: Array[String]) {
assertEquals(parseArgs(true, args), expected)
}

}
```