Skip to content

Commit

Permalink
Handle conversion of boolean query parameters with a value of "false"
Browse files Browse the repository at this point in the history
  • Loading branch information
csrwng committed Apr 30, 2015
1 parent a2fe8a9 commit a049ccb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pkg/runtime/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,17 @@ func convertStringSliceToInt(input *[]string, out *int, s conversion.Scope) erro
return nil
}

// converStringSliceToBool will convert a string parameter to boolean.
// Only the absence of a value, or a value of "false" and "0" resolve to false.
// Any other value (including empty string) resolves to true.
func convertStringSliceToBool(input *[]string, out *bool, s conversion.Scope) error {
if len(*input) == 0 {
*out = false
return nil
}
switch strings.ToLower((*input)[0]) {
case "true", "1":
*out = true
case "false", "0":
*out = false
default:
*out = true
}
Expand Down
32 changes: 32 additions & 0 deletions pkg/runtime/conversion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type InternalComplex struct {
Integer int
Integer64 int64
Int64 int64
Bool bool
}

type ExternalComplex struct {
Expand All @@ -37,6 +38,7 @@ type ExternalComplex struct {
Integer int `json:"int"`
Integer64 int64 `json:",omitempty"`
Int64 int64
Bool bool `json:"bool"`
}

func (*InternalComplex) IsAnAPIObject() {}
Expand Down Expand Up @@ -82,6 +84,36 @@ func TestStringMapConversion(t *testing.T) {
errFn: func(err error) bool { return err != nil },
expected: &ExternalComplex{},
},
"parses boolean true": {
input: map[string][]string{
"bool": {"true"},
},
expected: &ExternalComplex{Bool: true},
},
"parses boolean any value": {
input: map[string][]string{
"bool": {"foo"},
},
expected: &ExternalComplex{Bool: true},
},
"parses boolean false": {
input: map[string][]string{
"bool": {"false"},
},
expected: &ExternalComplex{Bool: false},
},
"parses boolean empty value": {
input: map[string][]string{
"bool": {""},
},
expected: &ExternalComplex{Bool: true},
},
"parses boolean no value": {
input: map[string][]string{
"bool": {},
},
expected: &ExternalComplex{Bool: false},
},
}

for k, tc := range testCases {
Expand Down

0 comments on commit a049ccb

Please sign in to comment.