Add test coverage for handling of numeric values by Plan.UnmarshalJSON (#111)
diff --git a/plan_test.go b/plan_test.go index 2f9b37c..1f59fc1 100644 --- a/plan_test.go +++ b/plan_test.go
@@ -120,3 +120,59 @@ t.Fatalf("unexpected previous address %s, expected is random_id.test", plan.ResourceChanges[0].PreviousAddress) } } + +func TestPlan_UnmarshalJSON(t *testing.T) { + t.Parallel() + + b, err := os.ReadFile("testdata/numerics/plan.json") + if err != nil { + t.Fatal(err) + } + + testCases := map[string]struct { + useJSONNumber bool + expected any + }{ + "float64": { + expected: 1.23, + }, + "json-number": { + useJSONNumber: true, + expected: json.Number("1.23"), + }, + } + + for name, testCase := range testCases { + name, testCase := name, testCase + + t.Run(name, func(t *testing.T) { + t.Parallel() + + plan := &Plan{} + + plan.UseJSONNumber(testCase.useJSONNumber) + + err = plan.UnmarshalJSON(b) + + if err != nil { + t.Fatal(err) + } + + after, ok := plan.ResourceChanges[0].Change.After.(map[string]any) + + if !ok { + t.Fatal("plan.ResourceChanges[0].Change.After cannot be asserted as map[string]any") + } + + attr, ok := after["configurable_attribute"] + + if !ok { + t.Fatal("configurable attribute not found") + } + + if diff := cmp.Diff(attr, testCase.expected); diff != "" { + t.Errorf("unexpected difference: %s", diff) + } + }) + } +}
diff --git a/testdata/numerics/plan.json b/testdata/numerics/plan.json new file mode 100644 index 0000000..41562eb --- /dev/null +++ b/testdata/numerics/plan.json
@@ -0,0 +1,75 @@ +{ + "format_version": "1.2", + "terraform_version": "1.6.5", + "planned_values": { + "root_module": { + "resources": [ + { + "address": "example_resource.test", + "mode": "managed", + "type": "example_resource", + "name": "test", + "provider_name": "registry.terraform.io/hashicorp/example", + "schema_version": 0, + "values": { + "configurable_attribute": 1.23, + "id": "one" + }, + "sensitive_values": {} + } + ] + } + }, + "resource_changes": [ + { + "address": "example_resource.test", + "mode": "managed", + "type": "example_resource", + "name": "test", + "provider_name": "registry.terraform.io/hashicorp/example", + "change": { + "actions": [ + "create" + ], + "before": null, + "after": { + "configurable_attribute": 1.23, + "id": "one" + }, + "after_unknown": {}, + "before_sensitive": false, + "after_sensitive": {} + } + } + ], + "configuration": { + "provider_config": { + "example": { + "name": "example", + "full_name": "registry.terraform.io/hashicorp/example" + } + }, + "root_module": { + "resources": [ + { + "address": "example_resource.test", + "mode": "managed", + "type": "example_resource", + "name": "test", + "provider_config_key": "example", + "expressions": { + "configurable_attribute": { + "constant_value": 1.23 + }, + "id": { + "constant_value": "one" + } + }, + "schema_version": 0 + } + ] + } + }, + "timestamp": "2023-12-07T13:55:56Z", + "errored": false +} \ No newline at end of file