Skip to content

Commit 5b915f2

Browse files
authored
helper/schema: Allow Schema with TypeInt to accept string values from DefaultFunc(). (#841)
This brings the int field up to par with bool and float ones. Fixes hashicorp/terraform-plugin-sdk#773
1 parent 0045c35 commit 5b915f2

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

helper/schema/schema.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2245,8 +2245,19 @@ func (m schemaMap) validatePrimitive(
22452245
// decode a float as an integer.
22462246

22472247
// the config shims only use int for integral number values
2248+
// also accept a string, just as the TypeBool and TypeFloat cases do
22482249
if v, ok := raw.(int); ok {
22492250
decoded = v
2251+
} else if _, ok := raw.(string); ok {
2252+
var n int
2253+
if err := mapstructure.WeakDecode(raw, &n); err != nil {
2254+
return append(diags, diag.Diagnostic{
2255+
Severity: diag.Error,
2256+
Summary: err.Error(),
2257+
AttributePath: path,
2258+
})
2259+
}
2260+
decoded = n
22502261
} else {
22512262
return append(diags, diag.Diagnostic{
22522263
Severity: diag.Error,
@@ -2255,7 +2266,7 @@ func (m schemaMap) validatePrimitive(
22552266
})
22562267
}
22572268
case TypeFloat:
2258-
// Verify that we can parse this as an int
2269+
// Verify that we can parse this as a float
22592270
var n float64
22602271
if err := mapstructure.WeakDecode(raw, &n); err != nil {
22612272
return append(diags, diag.Diagnostic{

helper/schema/schema_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6744,6 +6744,33 @@ func TestSchemaMap_Validate(t *testing.T) {
67446744
},
67456745
Err: true,
67466746
},
6747+
"bool with DefaultFunc that returns str": {
6748+
Schema: map[string]*Schema{
6749+
"bool_field": {
6750+
Type: TypeBool,
6751+
Optional: true,
6752+
DefaultFunc: func() (interface{}, error) { return "true", nil },
6753+
},
6754+
},
6755+
},
6756+
"float with DefaultFunc that returns str": {
6757+
Schema: map[string]*Schema{
6758+
"float_field": {
6759+
Type: TypeFloat,
6760+
Optional: true,
6761+
DefaultFunc: func() (interface{}, error) { return "1.23", nil },
6762+
},
6763+
},
6764+
},
6765+
"int with DefaultFunc that returns str": {
6766+
Schema: map[string]*Schema{
6767+
"int_field": {
6768+
Type: TypeInt,
6769+
Optional: true,
6770+
DefaultFunc: func() (interface{}, error) { return "1", nil },
6771+
},
6772+
},
6773+
},
67476774
}
67486775

67496776
for tn, tc := range cases {

0 commit comments

Comments
 (0)