From 77ef4504052f5bc66fbf0874ca31da50ae34cf34 Mon Sep 17 00:00:00 2001 From: Kazuma Watanabe Date: Sat, 6 Aug 2022 21:46:04 +0900 Subject: [PATCH] Add support for JSON syntax in TestRunner (#177) --- helper/runner_test.go | 33 +++++++++++++++++++++++++++++++++ helper/testing.go | 9 ++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/helper/runner_test.go b/helper/runner_test.go index a5f3828..6e35c80 100644 --- a/helper/runner_test.go +++ b/helper/runner_test.go @@ -247,6 +247,39 @@ terraform { } } +func Test_GetModuleContent_json(t *testing.T) { + files := map[string]string{ + "main.tf.json": `{"variable": {"foo": {"type": "string"}}}`, + } + + runner := TestRunner(t, files) + + schema := &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "variable", + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "type", + LabelNames: []string{"name"}, + Body: &hclext.BodySchema{}, + }, + }, + }, + }, + }, + } + got, err := runner.GetModuleContent(schema, nil) + if err != nil { + t.Error(err) + } else { + if len(got.Blocks) != 1 { + t.Errorf("got %d blocks, but 1 block is expected", len(got.Blocks)) + } + } +} + func Test_EvaluateExpr(t *testing.T) { tests := []struct { Name string diff --git a/helper/testing.go b/helper/testing.go index 13f7b93..e67ab91 100644 --- a/helper/testing.go +++ b/helper/testing.go @@ -3,6 +3,7 @@ package helper import ( "fmt" "reflect" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -20,7 +21,13 @@ func TestRunner(t *testing.T, files map[string]string) *Runner { parser := hclparse.NewParser() for name, src := range files { - file, diags := parser.ParseHCL([]byte(src), name) + var file *hcl.File + var diags hcl.Diagnostics + if strings.HasSuffix(name, ".json") { + file, diags = parser.ParseJSON([]byte(src), name) + } else { + file, diags = parser.ParseHCL([]byte(src), name) + } if diags.HasErrors() { t.Fatal(diags) }