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