Skip to content

Commit

Permalink
helper: Fix panic when helper runner uses variables (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
wata727 authored Mar 27, 2022
1 parent 1d4544f commit 919fa27
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 18 deletions.
2 changes: 1 addition & 1 deletion helper/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func (r *Runner) EnsureNoError(err error, proc func() error) error {
// NewLocalRunner initialises a new test runner.
// Internal use only.
func NewLocalRunner(files map[string]*hcl.File, issues Issues) *Runner {
return &Runner{files: map[string]*hcl.File{}, Issues: issues}
return &Runner{files: map[string]*hcl.File{}, variables: map[string]*Variable{}, Issues: issues}
}

// AddLocalFile adds a new file to the current mapped files.
Expand Down
60 changes: 43 additions & 17 deletions helper/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,29 +248,55 @@ terraform {
}

func Test_EvaluateExpr(t *testing.T) {
src := `
tests := []struct {
Name string
Src string
Want string
}{
{
Name: "string literal",
Src: `
resource "aws_instance" "foo" {
instance_type = "t2.micro"
}`

runner := TestRunner(t, map[string]string{"main.tf": src})
}`,
Want: "t2.micro",
},
{
Name: "string interpolation",
Src: `
variable "instance_type" {
default = "t2.micro"
}
resources, err := runner.GetResourceContent("aws_instance", &hclext.BodySchema{
Attributes: []hclext.AttributeSchema{{Name: "instance_type"}},
}, nil)
if err != nil {
t.Fatal(err)
resource "aws_instance" "foo" {
instance_type = var.instance_type
}`,
Want: "t2.micro",
},
}

for _, resource := range resources.Blocks {
var instanceType string
if err := runner.EvaluateExpr(resource.Body.Attributes["instance_type"].Expr, &instanceType, nil); err != nil {
t.Fatal(err)
}
for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
runner := TestRunner(t, map[string]string{"main.tf": test.Src})

if instanceType != "t2.micro" {
t.Fatalf(`expected value is "t2.micro", but got "%s"`, instanceType)
}
resources, err := runner.GetResourceContent("aws_instance", &hclext.BodySchema{
Attributes: []hclext.AttributeSchema{{Name: "instance_type"}},
}, nil)
if err != nil {
t.Fatal(err)
}

for _, resource := range resources.Blocks {
var instanceType string
if err := runner.EvaluateExpr(resource.Body.Attributes["instance_type"].Expr, &instanceType, nil); err != nil {
t.Fatal(err)
}

if instanceType != test.Want {
t.Fatalf(`"%s" is expected, but got "%s"`, test.Want, instanceType)
}
}
})
}
}

Expand Down

0 comments on commit 919fa27

Please sign in to comment.