github.com/arvindram03/terraform@v0.3.7-0.20150212015210-408f838db36d/config/lang/eval_test.go (about) 1 package lang 2 3 import ( 4 "reflect" 5 "strconv" 6 "testing" 7 8 "github.com/hashicorp/terraform/config/lang/ast" 9 ) 10 11 func TestEval(t *testing.T) { 12 cases := []struct { 13 Input string 14 Scope *ast.BasicScope 15 Error bool 16 Result interface{} 17 ResultType ast.Type 18 }{ 19 { 20 "foo", 21 nil, 22 false, 23 "foo", 24 ast.TypeString, 25 }, 26 27 { 28 "foo ${bar}", 29 &ast.BasicScope{ 30 VarMap: map[string]ast.Variable{ 31 "bar": ast.Variable{ 32 Value: "baz", 33 Type: ast.TypeString, 34 }, 35 }, 36 }, 37 false, 38 "foo baz", 39 ast.TypeString, 40 }, 41 42 { 43 "foo ${rand()}", 44 &ast.BasicScope{ 45 FuncMap: map[string]ast.Function{ 46 "rand": ast.Function{ 47 ReturnType: ast.TypeString, 48 Callback: func([]interface{}) (interface{}, error) { 49 return "42", nil 50 }, 51 }, 52 }, 53 }, 54 false, 55 "foo 42", 56 ast.TypeString, 57 }, 58 59 { 60 `foo ${rand("foo", "bar")}`, 61 &ast.BasicScope{ 62 FuncMap: map[string]ast.Function{ 63 "rand": ast.Function{ 64 ReturnType: ast.TypeString, 65 Variadic: true, 66 VariadicType: ast.TypeString, 67 Callback: func(args []interface{}) (interface{}, error) { 68 var result string 69 for _, a := range args { 70 result += a.(string) 71 } 72 return result, nil 73 }, 74 }, 75 }, 76 }, 77 false, 78 "foo foobar", 79 ast.TypeString, 80 }, 81 82 // Testing implicit type conversions 83 84 { 85 "foo ${bar}", 86 &ast.BasicScope{ 87 VarMap: map[string]ast.Variable{ 88 "bar": ast.Variable{ 89 Value: 42, 90 Type: ast.TypeInt, 91 }, 92 }, 93 }, 94 false, 95 "foo 42", 96 ast.TypeString, 97 }, 98 99 { 100 `foo ${foo("42")}`, 101 &ast.BasicScope{ 102 FuncMap: map[string]ast.Function{ 103 "foo": ast.Function{ 104 ArgTypes: []ast.Type{ast.TypeInt}, 105 ReturnType: ast.TypeString, 106 Callback: func(args []interface{}) (interface{}, error) { 107 return strconv.FormatInt(int64(args[0].(int)), 10), nil 108 }, 109 }, 110 }, 111 }, 112 false, 113 "foo 42", 114 ast.TypeString, 115 }, 116 } 117 118 for _, tc := range cases { 119 node, err := Parse(tc.Input) 120 if err != nil { 121 t.Fatalf("Error: %s\n\nInput: %s", err, tc.Input) 122 } 123 124 out, outType, err := Eval(node, &EvalConfig{GlobalScope: tc.Scope}) 125 if (err != nil) != tc.Error { 126 t.Fatalf("Error: %s\n\nInput: %s", err, tc.Input) 127 } 128 if outType != tc.ResultType { 129 t.Fatalf("Bad: %s\n\nInput: %s", outType, tc.Input) 130 } 131 if !reflect.DeepEqual(out, tc.Result) { 132 t.Fatalf("Bad: %#v\n\nInput: %s", out, tc.Input) 133 } 134 } 135 }