1package flags 2 3import ( 4 "fmt" 5 "testing" 6) 7 8type marshalled string 9 10func (m *marshalled) UnmarshalFlag(value string) error { 11 if value == "yes" { 12 *m = "true" 13 } else if value == "no" { 14 *m = "false" 15 } else { 16 return fmt.Errorf("`%s' is not a valid value, please specify `yes' or `no'", value) 17 } 18 19 return nil 20} 21 22func (m marshalled) MarshalFlag() (string, error) { 23 if m == "true" { 24 return "yes", nil 25 } 26 27 return "no", nil 28} 29 30type marshalledError bool 31 32func (m marshalledError) MarshalFlag() (string, error) { 33 return "", newErrorf(ErrMarshal, "Failed to marshal") 34} 35 36func TestUnmarshal(t *testing.T) { 37 var opts = struct { 38 Value marshalled `short:"v"` 39 }{} 40 41 ret := assertParseSuccess(t, &opts, "-v=yes") 42 43 assertStringArray(t, ret, []string{}) 44 45 if opts.Value != "true" { 46 t.Errorf("Expected Value to be \"true\"") 47 } 48} 49 50func TestUnmarshalDefault(t *testing.T) { 51 var opts = struct { 52 Value marshalled `short:"v" default:"yes"` 53 }{} 54 55 ret := assertParseSuccess(t, &opts) 56 57 assertStringArray(t, ret, []string{}) 58 59 if opts.Value != "true" { 60 t.Errorf("Expected Value to be \"true\"") 61 } 62} 63 64func TestUnmarshalOptional(t *testing.T) { 65 var opts = struct { 66 Value marshalled `short:"v" optional:"yes" optional-value:"yes"` 67 }{} 68 69 ret := assertParseSuccess(t, &opts, "-v") 70 71 assertStringArray(t, ret, []string{}) 72 73 if opts.Value != "true" { 74 t.Errorf("Expected Value to be \"true\"") 75 } 76} 77 78func TestUnmarshalError(t *testing.T) { 79 var opts = struct { 80 Value marshalled `short:"v"` 81 }{} 82 83 assertParseFail(t, ErrMarshal, fmt.Sprintf("invalid argument for flag `%cv' (expected flags.marshalled): `invalid' is not a valid value, please specify `yes' or `no'", defaultShortOptDelimiter), &opts, "-vinvalid") 84} 85 86func TestUnmarshalPositionalError(t *testing.T) { 87 var opts = struct { 88 Args struct { 89 Value marshalled 90 } `positional-args:"yes"` 91 }{} 92 93 parser := NewParser(&opts, Default&^PrintErrors) 94 _, err := parser.ParseArgs([]string{"invalid"}) 95 96 msg := "`invalid' is not a valid value, please specify `yes' or `no'" 97 98 if err == nil { 99 assertFatalf(t, "Expected error: %s", msg) 100 return 101 } 102 103 if err.Error() != msg { 104 assertErrorf(t, "Expected error message %#v, but got %#v", msg, err.Error()) 105 } 106} 107 108func TestMarshalError(t *testing.T) { 109 var opts = struct { 110 Value marshalledError `short:"v"` 111 }{} 112 113 p := NewParser(&opts, Default) 114 o := p.Command.Groups()[0].Options()[0] 115 116 _, err := convertToString(o.value, o.tag) 117 118 assertError(t, err, ErrMarshal, "Failed to marshal") 119} 120