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