|
| 1 | +package terraform |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/hashicorp/hcl/v2" |
| 7 | + "github.com/hashicorp/hcl/v2/hclsyntax" |
| 8 | + "github.com/hashicorp/terraform/addrs" |
| 9 | + "github.com/hashicorp/terraform/providers" |
| 10 | + "github.com/zclconf/go-cty/cty" |
| 11 | +) |
| 12 | + |
| 13 | +func TestContextEval(t *testing.T) { |
| 14 | + // This test doesn't check the "Want" value for impure funcs, so the value |
| 15 | + // on those doesn't matter. |
| 16 | + tests := []struct { |
| 17 | + Input string |
| 18 | + Want cty.Value |
| 19 | + ImpureFunc bool |
| 20 | + }{ |
| 21 | + { // An impure function: allowed in the console, but the result is nondeterministic |
| 22 | + `bcrypt("example")`, |
| 23 | + cty.NilVal, |
| 24 | + true, |
| 25 | + }, |
| 26 | + { |
| 27 | + `keys(var.map)`, |
| 28 | + cty.ListVal([]cty.Value{ |
| 29 | + cty.StringVal("foo"), |
| 30 | + cty.StringVal("baz"), |
| 31 | + }), |
| 32 | + true, |
| 33 | + }, |
| 34 | + { |
| 35 | + `local.result`, |
| 36 | + cty.NumberIntVal(6), |
| 37 | + false, |
| 38 | + }, |
| 39 | + { |
| 40 | + `module.child.result`, |
| 41 | + cty.UnknownVal(cty.Number), |
| 42 | + false, |
| 43 | + }, |
| 44 | + } |
| 45 | + |
| 46 | + // This module has a little bit of everything (and if it is missing somehitng, add to it): |
| 47 | + // resources, variables, locals, modules, output |
| 48 | + m := testModule(t, "eval-context-basic") |
| 49 | + p := testProvider("test") |
| 50 | + ctx := testContext2(t, &ContextOpts{ |
| 51 | + Config: m, |
| 52 | + Providers: map[addrs.Provider]providers.Factory{ |
| 53 | + addrs.NewDefaultProvider("test"): testProviderFuncFixed(p), |
| 54 | + }, |
| 55 | + }) |
| 56 | + |
| 57 | + scope, diags := ctx.Eval(addrs.RootModuleInstance) |
| 58 | + if diags.HasErrors() { |
| 59 | + t.Fatalf("Eval errors: %s", diags.Err()) |
| 60 | + } |
| 61 | + |
| 62 | + // Since we're testing 'eval' (used by terraform console), impure functions |
| 63 | + // should be allowed by the scope. |
| 64 | + if scope.PureOnly == true { |
| 65 | + t.Fatal("wrong result: eval should allow impure funcs") |
| 66 | + } |
| 67 | + |
| 68 | + for _, test := range tests { |
| 69 | + t.Run(test.Input, func(t *testing.T) { |
| 70 | + // Parse the test input as an expression |
| 71 | + expr, _ := hclsyntax.ParseExpression([]byte(test.Input), "<test-input>", hcl.Pos{Line: 1, Column: 1}) |
| 72 | + got, diags := scope.EvalExpr(expr, cty.DynamicPseudoType) |
| 73 | + |
| 74 | + if diags.HasErrors() { |
| 75 | + t.Fatalf("unexpected error: %s", diags.Err()) |
| 76 | + } |
| 77 | + |
| 78 | + if !test.ImpureFunc { |
| 79 | + if !got.RawEquals(test.Want) { |
| 80 | + t.Fatalf("wrong result: want %#v, got %#v", test.Want, got) |
| 81 | + } |
| 82 | + } |
| 83 | + }) |
| 84 | + } |
| 85 | +} |
0 commit comments