github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/mysql/resource_user_test.go (about) 1 package mysql 2 3 import ( 4 "fmt" 5 "log" 6 "testing" 7 8 "github.com/hashicorp/terraform/helper/resource" 9 "github.com/hashicorp/terraform/terraform" 10 ) 11 12 func TestAccUser(t *testing.T) { 13 resource.Test(t, resource.TestCase{ 14 PreCheck: func() { testAccPreCheck(t) }, 15 Providers: testAccProviders, 16 CheckDestroy: testAccUserCheckDestroy, 17 Steps: []resource.TestStep{ 18 resource.TestStep{ 19 Config: testAccUserConfig_basic, 20 Check: resource.ComposeTestCheckFunc( 21 testAccUserExists("mysql_user.test"), 22 resource.TestCheckResourceAttr("mysql_user.test", "user", "jdoe"), 23 resource.TestCheckResourceAttr("mysql_user.test", "host", "example.com"), 24 resource.TestCheckResourceAttr("mysql_user.test", "password", "password"), 25 ), 26 }, 27 resource.TestStep{ 28 Config: testAccUserConfig_newPass, 29 Check: resource.ComposeTestCheckFunc( 30 testAccUserExists("mysql_user.test"), 31 resource.TestCheckResourceAttr("mysql_user.test", "user", "jdoe"), 32 resource.TestCheckResourceAttr("mysql_user.test", "host", "example.com"), 33 resource.TestCheckResourceAttr("mysql_user.test", "password", "password2"), 34 ), 35 }, 36 }, 37 }) 38 } 39 40 func testAccUserExists(rn string) resource.TestCheckFunc { 41 return func(s *terraform.State) error { 42 rs, ok := s.RootModule().Resources[rn] 43 if !ok { 44 return fmt.Errorf("resource not found: %s", rn) 45 } 46 47 if rs.Primary.ID == "" { 48 return fmt.Errorf("user id not set") 49 } 50 51 conn := testAccProvider.Meta().(*providerConfiguration).Conn 52 stmtSQL := fmt.Sprintf("SELECT count(*) from mysql.user where CONCAT(user, '@', host) = '%s'", rs.Primary.ID) 53 log.Println("Executing statement:", stmtSQL) 54 rows, _, err := conn.Query(stmtSQL) 55 if err != nil { 56 return fmt.Errorf("error reading user: %s", err) 57 } 58 if len(rows) != 1 { 59 return fmt.Errorf("expected 1 row reading user but got %d", len(rows)) 60 } 61 62 return nil 63 } 64 } 65 66 func testAccUserCheckDestroy(s *terraform.State) error { 67 conn := testAccProvider.Meta().(*providerConfiguration).Conn 68 69 for _, rs := range s.RootModule().Resources { 70 if rs.Type != "mysql_user" { 71 continue 72 } 73 74 stmtSQL := fmt.Sprintf("SELECT user from mysql.user where CONCAT(user, '@', host) = '%s'", rs.Primary.ID) 75 log.Println("Executing statement:", stmtSQL) 76 rows, _, err := conn.Query(stmtSQL) 77 if err != nil { 78 return fmt.Errorf("error issuing query: %s", err) 79 } 80 if len(rows) != 0 { 81 return fmt.Errorf("user still exists after destroy") 82 } 83 } 84 return nil 85 } 86 87 const testAccUserConfig_basic = ` 88 resource "mysql_user" "test" { 89 user = "jdoe" 90 host = "example.com" 91 password = "password" 92 } 93 ` 94 95 const testAccUserConfig_newPass = ` 96 resource "mysql_user" "test" { 97 user = "jdoe" 98 host = "example.com" 99 password = "password2" 100 } 101 `