github.com/terraform-linters/tflint-plugin-sdk@v0.22.0/hclext/parse_test.go (about) 1 package hclext 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/hashicorp/hcl/v2" 8 ) 9 10 func TestParseExpression(t *testing.T) { 11 tests := []struct { 12 Name string 13 Source string 14 Filename string 15 Want string 16 DiagCount int 17 }{ 18 { 19 Name: "HCL (*.tf)", 20 Source: `"foo"`, 21 Filename: "test.tf", 22 Want: `cty.StringVal("foo")`, 23 DiagCount: 0, 24 }, 25 { 26 Name: "HCL (*.hcl)", 27 Source: `"bar"`, 28 Filename: "test.hcl", 29 Want: `cty.StringVal("bar")`, 30 DiagCount: 0, 31 }, 32 { 33 Name: "HCL but file extension is invalid (*.json)", 34 Source: `"baz"`, 35 Filename: "test.json", 36 DiagCount: 1, 37 }, 38 { 39 Name: "HCL heredoc with trailing newline", 40 Source: `<<EOF 41 foo 42 EOF 43 `, 44 Filename: "test.tf", 45 Want: `cty.StringVal("foo\n")`, 46 DiagCount: 0, 47 }, 48 { 49 Name: "HCL heredoc without trailing newline", 50 Source: `<<EOF 51 foo 52 EOF`, 53 Filename: "test.tf", 54 Want: `cty.StringVal("foo\n")`, 55 DiagCount: 0, 56 }, 57 { 58 Name: "json", 59 Source: `{"foo":"bar","baz":1}`, 60 Filename: "test.tf.json", 61 Want: `cty.ObjectVal(map[string]cty.Value{"baz":cty.NumberIntVal(1), "foo":cty.StringVal("bar")})`, 62 DiagCount: 0, 63 }, 64 } 65 66 for _, test := range tests { 67 t.Run(test.Name, func(t *testing.T) { 68 expr, diags := ParseExpression([]byte(test.Source), test.Filename, hcl.InitialPos) 69 if len(diags) != test.DiagCount { 70 t.Errorf("wrong number of diagnostics %d; want %d", len(diags), test.DiagCount) 71 for _, diag := range diags { 72 t.Logf(" - %s", diag.Error()) 73 } 74 } 75 if diags.HasErrors() { 76 return 77 } 78 79 value, diags := expr.Value(nil) 80 if diags.HasErrors() { 81 t.Errorf("got %d diagnostics on decode value; want 0", len(diags)) 82 for _, d := range diags { 83 t.Logf(" - %s", d.Error()) 84 } 85 } 86 87 got := fmt.Sprintf("%#v", value) 88 if got != test.Want { 89 t.Errorf("got %s, but want %s", got, test.Want) 90 } 91 }) 92 } 93 }