github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/external/data_source_test.go (about) 1 package external 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "path" 8 "regexp" 9 "testing" 10 11 "github.com/hashicorp/terraform/helper/resource" 12 "github.com/hashicorp/terraform/terraform" 13 ) 14 15 const testDataSourceConfig_basic = ` 16 data "external" "test" { 17 program = ["%s", "cheese"] 18 19 query = { 20 value = "pizza" 21 } 22 } 23 24 output "query_value" { 25 value = "${data.external.test.result["query_value"]}" 26 } 27 28 output "argument" { 29 value = "${data.external.test.result["argument"]}" 30 } 31 ` 32 33 func TestDataSource_basic(t *testing.T) { 34 programPath, err := buildDataSourceTestProgram() 35 if err != nil { 36 t.Fatal(err) 37 return 38 } 39 40 resource.UnitTest(t, resource.TestCase{ 41 Providers: testProviders, 42 Steps: []resource.TestStep{ 43 resource.TestStep{ 44 Config: fmt.Sprintf(testDataSourceConfig_basic, programPath), 45 Check: func(s *terraform.State) error { 46 _, ok := s.RootModule().Resources["data.external.test"] 47 if !ok { 48 return fmt.Errorf("missing data resource") 49 } 50 51 outputs := s.RootModule().Outputs 52 53 if outputs["argument"] == nil { 54 return fmt.Errorf("missing 'argument' output") 55 } 56 if outputs["query_value"] == nil { 57 return fmt.Errorf("missing 'query_value' output") 58 } 59 60 if outputs["argument"].Value != "cheese" { 61 return fmt.Errorf( 62 "'argument' output is %q; want 'cheese'", 63 outputs["argument"].Value, 64 ) 65 } 66 if outputs["query_value"].Value != "pizza" { 67 return fmt.Errorf( 68 "'query_value' output is %q; want 'pizza'", 69 outputs["query_value"].Value, 70 ) 71 } 72 73 return nil 74 }, 75 }, 76 }, 77 }) 78 } 79 80 const testDataSourceConfig_error = ` 81 data "external" "test" { 82 program = ["%s"] 83 84 query = { 85 fail = "true" 86 } 87 } 88 ` 89 90 func TestDataSource_error(t *testing.T) { 91 programPath, err := buildDataSourceTestProgram() 92 if err != nil { 93 t.Fatal(err) 94 return 95 } 96 97 resource.UnitTest(t, resource.TestCase{ 98 Providers: testProviders, 99 Steps: []resource.TestStep{ 100 resource.TestStep{ 101 Config: fmt.Sprintf(testDataSourceConfig_error, programPath), 102 ExpectError: regexp.MustCompile("I was asked to fail"), 103 }, 104 }, 105 }) 106 } 107 108 func buildDataSourceTestProgram() (string, error) { 109 // We have a simple Go program that we use as a stub for testing. 110 cmd := exec.Command( 111 "go", "install", 112 "github.com/hashicorp/terraform/builtin/providers/external/test-programs/tf-acc-external-data-source", 113 ) 114 err := cmd.Run() 115 116 if err != nil { 117 return "", fmt.Errorf("failed to build test stub program: %s", err) 118 } 119 120 programPath := path.Join( 121 os.Getenv("GOPATH"), "bin", "tf-acc-external-data-source", 122 ) 123 return programPath, nil 124 }