TestHCLDecDecodeToExpr tests both hcldec's support for types with custom expression decoding rules and the two expression capsule types implemented in ext/customdecode. This mechanism requires cooperation between those two components and cty in order to work, so it's helpful to exercise it in an int
(t *testing.T)
| 21 | // two components and cty in order to work, so it's helpful to exercise it in |
| 22 | // an integration test. |
| 23 | func TestHCLDecDecodeToExpr(t *testing.T) { |
| 24 | // Here we're going to capture the structure of two simple expressions |
| 25 | // without immediately evaluating them. |
| 26 | const input = ` |
| 27 | a = foo |
| 28 | b = foo |
| 29 | c = "hello" |
| 30 | ` |
| 31 | // We'll capture "a" directly as an expression, losing its evaluation |
| 32 | // context but retaining its structure. We'll capture "b" as a |
| 33 | // customdecode.ExpressionClosure, which gives us both the expression |
| 34 | // itself and the evaluation context it was originally evaluated in. |
| 35 | // We also have "c" here just to make sure we can still decode into a |
| 36 | // "normal" type via standard expression evaluation. |
| 37 | |
| 38 | f, diags := hclsyntax.ParseConfig([]byte(input), "", hcl.Pos{Line: 1, Column: 1}) |
| 39 | if diags.HasErrors() { |
| 40 | t.Fatalf("unexpected problems: %s", diags.Error()) |
| 41 | } |
| 42 | |
| 43 | spec := hcldec.ObjectSpec{ |
| 44 | "a": &hcldec.AttrSpec{ |
| 45 | Name: "a", |
| 46 | Type: customdecode.ExpressionType, |
| 47 | Required: true, |
| 48 | }, |
| 49 | "b": &hcldec.AttrSpec{ |
| 50 | Name: "b", |
| 51 | Type: customdecode.ExpressionClosureType, |
| 52 | Required: true, |
| 53 | }, |
| 54 | "c": &hcldec.AttrSpec{ |
| 55 | Name: "c", |
| 56 | Type: cty.String, |
| 57 | Required: true, |
| 58 | }, |
| 59 | } |
| 60 | ctx := &hcl.EvalContext{ |
| 61 | Variables: map[string]cty.Value{ |
| 62 | "foo": cty.StringVal("foo value"), |
| 63 | }, |
| 64 | } |
| 65 | objVal, diags := hcldec.Decode(f.Body, spec, ctx) |
| 66 | if diags.HasErrors() { |
| 67 | t.Fatalf("unexpected problems: %s", diags.Error()) |
| 68 | } |
| 69 | |
| 70 | aVal := objVal.GetAttr("a") |
| 71 | bVal := objVal.GetAttr("b") |
| 72 | cVal := objVal.GetAttr("c") |
| 73 | |
| 74 | if got, want := aVal.Type(), customdecode.ExpressionType; !got.Equals(want) { |
| 75 | t.Fatalf("wrong type for 'a'\ngot: %#v\nwant: %#v", got, want) |
| 76 | } |
| 77 | if got, want := bVal.Type(), customdecode.ExpressionClosureType; !got.Equals(want) { |
| 78 | t.Fatalf("wrong type for 'b'\ngot: %#v\nwant: %#v", got, want) |
| 79 | } |
| 80 | if got, want := cVal.Type(), cty.String; !got.Equals(want) { |
nothing calls this directly
no test coverage detected