pulumi/pkg/codegen/hcl2/rewrite_convert_test.go
Pat Gavlin 33258326e0
[codegen/hcl2] Add a conversion insertion pass. (#4594)
Add a rewriter that reifies implicit conversions into a call to the
`__convert` intrinsic. Code generators can recognize this intrinsic and
use it to generate appropriate conversion code.

Part of this work involves redesigning the type annotations system.
Annotations are now only applicable to opaque and object types. Instead
of inspecting annotations directly, code generators should use
`hcl2.GetSchemaForType` to extract the `schema.Type` for a `model.Type`.
2020-05-11 11:17:36 -07:00

65 lines
1.4 KiB
Go

package hcl2
import (
"fmt"
"testing"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi/pkg/v2/codegen/hcl2/model"
"github.com/pulumi/pulumi/pkg/v2/codegen/hcl2/syntax"
"github.com/pulumi/pulumi/pkg/v2/codegen/schema"
"github.com/stretchr/testify/assert"
)
func TestRewriteConversions(t *testing.T) {
cases := []struct {
input, output string
to model.Type
}{
{
input: `"1" + 2`,
output: `__convert("1") + 2`,
},
{
input: `{a: "b"}`,
output: `{a: "b"}`,
to: model.NewObjectType(map[string]model.Type{
"a": model.StringType,
}),
},
{
input: `{a: "b"}`,
output: `{a: "b"}`,
to: model.InputType(model.NewObjectType(map[string]model.Type{
"a": model.StringType,
})),
},
{
input: `{a: "b"}`,
output: `__convert({a: "b"})`,
to: model.NewObjectType(map[string]model.Type{
"a": model.StringType,
}, &schema.ObjectType{}),
},
{
input: `{a: "b"}`,
output: `__convert({a: "b"})`,
to: model.InputType(model.NewObjectType(map[string]model.Type{
"a": model.StringType,
}, &schema.ObjectType{})),
},
}
scope := model.NewRootScope(syntax.None)
for _, c := range cases {
expr, diags := model.BindExpressionText(c.input, scope, hcl.Pos{})
assert.Len(t, diags, 0)
to := c.to
if to == nil {
to = expr.Type()
}
expr = RewriteConversions(expr, to)
assert.Equal(t, c.output, fmt.Sprintf("%v", expr))
}
}