github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/builtin/providers/template/resource_test.go (about)

     1  package template
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	r "github.com/hashicorp/terraform/helper/resource"
     8  	"github.com/hashicorp/terraform/terraform"
     9  )
    10  
    11  var testProviders = map[string]terraform.ResourceProvider{
    12  	"template": Provider(),
    13  }
    14  
    15  func TestTemplateRendering(t *testing.T) {
    16  	var cases = []struct {
    17  		vars     string
    18  		template string
    19  		want     string
    20  	}{
    21  		{`{}`, `ABC`, `ABC`},
    22  		{`{a="foo"}`, `${a}`, `foo`},
    23  		{`{a="hello"}`, `${replace(a, "ello", "i")}`, `hi`},
    24  		{`{}`, `${1+2+3}`, `6`},
    25  	}
    26  
    27  	for _, tt := range cases {
    28  		r.Test(t, r.TestCase{
    29  			Providers: testProviders,
    30  			Steps: []r.TestStep{
    31  				r.TestStep{
    32  					Config: testTemplateConfig(tt.template, tt.vars),
    33  					Check: func(s *terraform.State) error {
    34  						got := s.RootModule().Outputs["rendered"]
    35  						if tt.want != got {
    36  							return fmt.Errorf("template:\n%s\nvars:\n%s\ngot:\n%s\nwant:\n%s\n", tt.template, tt.vars, got, tt.want)
    37  						}
    38  						return nil
    39  					},
    40  				},
    41  			},
    42  		})
    43  	}
    44  }
    45  
    46  // https://github.com/hashicorp/terraform/issues/2344
    47  func TestTemplateVariableChange(t *testing.T) {
    48  	steps := []struct {
    49  		vars     string
    50  		template string
    51  		want     string
    52  	}{
    53  		{`{a="foo"}`, `${a}`, `foo`},
    54  		{`{b="bar"}`, `${b}`, `bar`},
    55  	}
    56  
    57  	var testSteps []r.TestStep
    58  	for i, step := range steps {
    59  		testSteps = append(testSteps, r.TestStep{
    60  			Config: testTemplateConfig(step.template, step.vars),
    61  			Check: func(i int, want string) r.TestCheckFunc {
    62  				return func(s *terraform.State) error {
    63  					got := s.RootModule().Outputs["rendered"]
    64  					if want != got {
    65  						return fmt.Errorf("[%d] got:\n%q\nwant:\n%q\n", i, got, want)
    66  					}
    67  					return nil
    68  				}
    69  			}(i, step.want),
    70  		})
    71  	}
    72  
    73  	r.Test(t, r.TestCase{
    74  		Providers: testProviders,
    75  		Steps:     testSteps,
    76  	})
    77  }
    78  
    79  func testTemplateConfig(template, vars string) string {
    80  	return fmt.Sprintf(`
    81  		resource "template_file" "t0" {
    82  			template = "%s"
    83  			vars = %s
    84  		}
    85  		output "rendered" {
    86  				value = "${template_file.t0.rendered}"
    87  		}`, template, vars)
    88  }