Skip to content

Commit

Permalink
Implement boolean coercion
Browse files Browse the repository at this point in the history
Implements coercion to booleans along with the existing support for
integers.
  • Loading branch information
brandur committed Aug 3, 2017
1 parent 1c3d7ad commit bc203f4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
28 changes: 21 additions & 7 deletions param/coercer/coercer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (
// CoerceParams coerces the types of certain parameters according to typing
// information from their corresponding JSON schema. This is useful because an
// input format like form-encoding doesn't support anything but strings, and
// we'd like to work with a slightly wider variety of types like integers.
// we'd like to work with a slightly wider variety of types like booleans and
// integers.
//
// Currently only the coercion of strings to int64 is supported.
// Currently only the coercion of strings to bool and int64 is supported.
func CoerceParams(schema *spec.JSONSchema, data map[string]interface{}) {
for key, subSchema := range schema.Properties {
val, ok := data[key]
Expand All @@ -26,12 +27,22 @@ func CoerceParams(schema *spec.JSONSchema, data map[string]interface{}) {
}

valStr, ok := val.(string)
if ok && hasType(subSchema, integerType) {
valInt, err := strconv.Atoi(valStr)
if err != nil {
valInt = 0
if ok {
switch {
case hasType(subSchema, booleanType):
valBool, err := strconv.ParseBool(valStr)
if err != nil {
valBool = false
}
data[key] = valBool

case hasType(subSchema, integerType):
valInt, err := strconv.Atoi(valStr)
if err != nil {
valInt = 0
}
data[key] = valInt
}
data[key] = valInt
}
}
}
Expand All @@ -40,6 +51,9 @@ func CoerceParams(schema *spec.JSONSchema, data map[string]interface{}) {
// ---
//

// booleanType is the name of the boolean type in a JSON schema.
const booleanType = "boolean"

// integerType is the name of the integer type in a JSON schema.
const integerType = "integer"

Expand Down
12 changes: 12 additions & 0 deletions param/coercer/coercer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ import (
"github.com/stripe/stripe-mock/spec"
)

func TestCoerceParams_BooleanCoercion(t *testing.T) {
schema := &spec.JSONSchema{Properties: map[string]*spec.JSONSchema{
"boolkey": {Type: []string{booleanType}},
}}
data := map[string]interface{}{
"boolkey": "true",
}

CoerceParams(schema, data)
assert.Equal(t, true, data["boolkey"])
}

func TestCoerceParams_IntegerCoercion(t *testing.T) {
schema := &spec.JSONSchema{Properties: map[string]*spec.JSONSchema{
"intkey": {Type: []string{integerType}},
Expand Down

0 comments on commit bc203f4

Please sign in to comment.