github.com/mehmetalisavas/terraform@v0.7.10/builtin/providers/postgresql/resource_postgresql_extension_test.go (about) 1 package postgresql 2 3 import ( 4 "database/sql" 5 "fmt" 6 "testing" 7 8 "github.com/hashicorp/terraform/helper/resource" 9 "github.com/hashicorp/terraform/terraform" 10 ) 11 12 func TestAccPostgresqlExtension_Basic(t *testing.T) { 13 14 resource.Test(t, resource.TestCase{ 15 PreCheck: func() { testAccPreCheck(t) }, 16 Providers: testAccProviders, 17 CheckDestroy: testAccCheckPostgresqlExtensionDestroy, 18 Steps: []resource.TestStep{ 19 { 20 Config: testAccPostgresqlExtensionConfig, 21 Check: resource.ComposeTestCheckFunc( 22 testAccCheckPostgresqlExtensionExists("postgresql_extension.myextension"), 23 resource.TestCheckResourceAttr( 24 "postgresql_extension.myextension", "name", "pg_trgm"), 25 ), 26 }, 27 }, 28 }) 29 } 30 31 func testAccCheckPostgresqlExtensionDestroy(s *terraform.State) error { 32 client := testAccProvider.Meta().(*Client) 33 34 for _, rs := range s.RootModule().Resources { 35 if rs.Type != "postgresql_extension" { 36 continue 37 } 38 39 exists, err := checkExtensionExists(client, rs.Primary.ID) 40 41 if err != nil { 42 return fmt.Errorf("Error checking extension %s", err) 43 } 44 45 if exists { 46 return fmt.Errorf("Extension still exists after destroy") 47 } 48 } 49 50 return nil 51 } 52 53 func testAccCheckPostgresqlExtensionExists(n string) resource.TestCheckFunc { 54 return func(s *terraform.State) error { 55 rs, ok := s.RootModule().Resources[n] 56 if !ok { 57 return fmt.Errorf("Resource not found: %s", n) 58 } 59 60 if rs.Primary.ID == "" { 61 return fmt.Errorf("No ID is set") 62 } 63 64 client := testAccProvider.Meta().(*Client) 65 exists, err := checkExtensionExists(client, rs.Primary.ID) 66 67 if err != nil { 68 return fmt.Errorf("Error checking extension %s", err) 69 } 70 71 if !exists { 72 return fmt.Errorf("Extension not found") 73 } 74 75 return nil 76 } 77 } 78 79 func checkExtensionExists(client *Client, extensionName string) (bool, error) { 80 conn, err := client.Connect() 81 if err != nil { 82 return false, err 83 } 84 defer conn.Close() 85 86 var _rez int 87 err = conn.QueryRow("SELECT 1 from pg_extension d WHERE extname=$1", extensionName).Scan(&_rez) 88 switch { 89 case err == sql.ErrNoRows: 90 return false, nil 91 case err != nil: 92 return false, fmt.Errorf("Error reading info about extension: %s", err) 93 default: 94 return true, nil 95 } 96 } 97 98 var testAccPostgresqlExtensionConfig = ` 99 resource "postgresql_extension" "myextension" { 100 name = "pg_trgm" 101 } 102 `