From ba095896ac8d49de6e86d20ffd723d02a5733a3f Mon Sep 17 00:00:00 2001 From: mpeterv Date: Tue, 21 Jan 2014 23:02:58 +0400 Subject: [PATCH] added some tests for usage generation --- spec/usage_spec.lua | 87 +++++++++++++++++++++++++++++++++++++++++++++ src/argparse.lua | 4 +++ 2 files changed, 91 insertions(+) create mode 100644 spec/usage_spec.lua diff --git a/spec/usage_spec.lua b/spec/usage_spec.lua new file mode 100644 index 0000000..1338d72 --- /dev/null +++ b/spec/usage_spec.lua @@ -0,0 +1,87 @@ +local argparse = require "argparse" + +describe("tests related to usage message generation", function() + it("creates correct usage message for empty parser", function() + local parser = argparse.parser "foo" + assert.equal(parser:prepare():get_usage(), "Usage: foo") + end) + + it("creates correct usage message for arguments", function() + local parser = argparse.parser "foo" + parser:argument "first" + parser:argument "second-and-third" { + args = 2 + } + parser:argument "maybe-fourth" { + args = "?" + } + parser:argument "others" { + args = "*" + } + assert.equal( + [=[Usage: foo [] [] ...]=], + parser:prepare():get_usage() + ) + end) + + it("creates correct usage message for options", function() + local parser = argparse.parser "foo" + parser:flag "-q" "--quiet" + parser:option "--from" { + count = 1, + target = "server" + } + parser:option "--config" + assert.equal( + [=[Usage: foo [-q] --from [--config ]]=], + parser:prepare():get_usage() + ) + end) + + it("creates correct usage message for commands", function() + local parser = argparse.parser "foo" + parser:flag "-q" "--quiet" + local run = parser:command "run" + run:option "--where" + assert.equal( + [=[Usage: foo [-q] [] ...]=], + parser:prepare():get_usage() + ) + end) + + describe("usage generation can be customized", function() + it("uses message provided by user", function() + local parser = argparse.parser "foo" { + usage = "Usage: obvious" + } + parser:flag "-q" "--quiet" + assert.equal( + [=[Usage: obvious]=], + parser:prepare():get_usage() + ) + end) + + it("uses per-option message provided by user", function() + local parser = argparse.parser "foo" + parser:flag "-q" "--quiet" { + usage = "[-q | --quiet]" + } + assert.equal( + [=[Usage: foo [-q | --quiet]]=], + parser:prepare():get_usage() + ) + end) + + it("uses argnames provided by user", function() + local parser = argparse.parser "foo" + parser:argument "inputs" { + args = "1-2", + argname = "" + } + assert.equal( + [=[Usage: foo []]=], + parser:prepare():get_usage() + ) + end) + end) +end) diff --git a/src/argparse.lua b/src/argparse.lua index 1d722b0..4f67da2 100644 --- a/src/argparse.lua +++ b/src/argparse.lua @@ -93,6 +93,10 @@ function Argument:get_arg_usage(argname) while i <= math.min(self.maxargs, 3) do table.insert(buf, "[" .. argname .. "]") i = i+1 + + if self.maxargs == math.huge then + break + end end if i < self.maxargs then