1require_relative 'test_optparse'
2
3module TestOptionParser::ReqArg
4  class Def1 < TestOptionParser
5    include ReqArg
6    def setup
7      super
8      @opt.def_option("-xVAL") {|x| @flag = x}
9      @opt.def_option("--option=VAL") {|x| @flag = x}
10      @opt.def_option("--regexp=REGEXP", Regexp) {|x| @reopt = x}
11      @reopt = nil
12    end
13  end
14  class Def2 < TestOptionParser
15    include ReqArg
16    def setup
17      super
18      @opt.def_option("-x", "--option=VAL") {|x| @flag = x}
19    end
20  end
21  class Def3 < TestOptionParser
22    include ReqArg
23    def setup
24      super
25      @opt.def_option("--option=VAL", "-x") {|x| @flag = x}
26    end
27  end
28  class Def4 < TestOptionParser
29    include ReqArg
30    def setup
31      super
32      @opt.def_option("-xVAL", "--option=VAL") {|x| @flag = x}
33    end
34  end
35
36  def test_short
37    assert_raise(OptionParser::MissingArgument) {@opt.parse!(%w"-x")}
38    assert_equal(%w"", no_error {@opt.parse!(%w"-x foo")})
39    assert_equal("foo", @flag)
40    assert_equal(%w"", no_error {@opt.parse!(%w"-xbar")})
41    assert_equal("bar", @flag)
42    assert_equal(%w"", no_error {@opt.parse!(%w"-x=")})
43    assert_equal("=", @flag)
44  end
45
46  def test_abbrev
47    assert_raise(OptionParser::MissingArgument) {@opt.parse!(%w"-o")}
48    assert_equal(%w"", no_error {@opt.parse!(%w"-o foo")})
49    assert_equal("foo", @flag)
50    assert_equal(%w"", no_error {@opt.parse!(%w"-obar")})
51    assert_equal("bar", @flag)
52    assert_equal(%w"", no_error {@opt.parse!(%w"-o=")})
53    assert_equal("=", @flag)
54  end
55
56  def test_long
57    assert_raise(OptionParser::MissingArgument) {@opt.parse!(%w"--opt")}
58    assert_equal(%w"", no_error {@opt.parse!(%w"--opt foo")})
59    assert_equal("foo", @flag)
60    assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt= foo")})
61    assert_equal("", @flag)
62    assert_equal(%w"", no_error {@opt.parse!(%w"--opt=foo")})
63    assert_equal("foo", @flag)
64  end
65
66  class TestOptionParser::WithPattern < TestOptionParser
67    def test_pattern
68      pat = num = nil
69      @opt.def_option("--pattern=VAL", /(\w+)(?:\s*:\s*(\w+))?/) {|x, y, z| pat = [x, y, z]}
70      @opt.def_option("-T NUM", /\A[1-4]\z/) {|n| num = n}
71      no_error {@opt.parse!(%w"--pattern=key:val")}
72      assert_equal(%w"key:val key val", pat, '[ruby-list:45645]')
73      no_error {@opt.parse!(%w"-T 4")}
74      assert_equal("4", num, '[ruby-dev:37514]')
75    end
76  end
77end
78