Skip to content

Commit

Permalink
helper/schema: Allow Schema with TypeInt to accept string values from…
Browse files Browse the repository at this point in the history
… DefaultFunc(). (#841)

This brings the int field up to par with bool and float ones.

Fixes #773
  • Loading branch information
rudo-thomas committed Mar 24, 2022
1 parent 0045c35 commit 5b915f2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
13 changes: 12 additions & 1 deletion helper/schema/schema.go
Expand Up @@ -2245,8 +2245,19 @@ func (m schemaMap) validatePrimitive(
// decode a float as an integer.

// the config shims only use int for integral number values
// also accept a string, just as the TypeBool and TypeFloat cases do
if v, ok := raw.(int); ok {
decoded = v
} else if _, ok := raw.(string); ok {
var n int
if err := mapstructure.WeakDecode(raw, &n); err != nil {
return append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: err.Error(),
AttributePath: path,
})
}
decoded = n
} else {
return append(diags, diag.Diagnostic{
Severity: diag.Error,
Expand All @@ -2255,7 +2266,7 @@ func (m schemaMap) validatePrimitive(
})
}
case TypeFloat:
// Verify that we can parse this as an int
// Verify that we can parse this as a float
var n float64
if err := mapstructure.WeakDecode(raw, &n); err != nil {
return append(diags, diag.Diagnostic{
Expand Down
27 changes: 27 additions & 0 deletions helper/schema/schema_test.go
Expand Up @@ -6744,6 +6744,33 @@ func TestSchemaMap_Validate(t *testing.T) {
},
Err: true,
},
"bool with DefaultFunc that returns str": {
Schema: map[string]*Schema{
"bool_field": {
Type: TypeBool,
Optional: true,
DefaultFunc: func() (interface{}, error) { return "true", nil },
},
},
},
"float with DefaultFunc that returns str": {
Schema: map[string]*Schema{
"float_field": {
Type: TypeFloat,
Optional: true,
DefaultFunc: func() (interface{}, error) { return "1.23", nil },
},
},
},
"int with DefaultFunc that returns str": {
Schema: map[string]*Schema{
"int_field": {
Type: TypeInt,
Optional: true,
DefaultFunc: func() (interface{}, error) { return "1", nil },
},
},
},
}

for tn, tc := range cases {
Expand Down

0 comments on commit 5b915f2

Please sign in to comment.