github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/digitalocean/resource_digitalocean_ssh_key_test.go (about) 1 package digitalocean 2 3 import ( 4 "fmt" 5 "strconv" 6 "testing" 7 8 "github.com/digitalocean/godo" 9 "github.com/hashicorp/terraform/helper/acctest" 10 "github.com/hashicorp/terraform/helper/resource" 11 "github.com/hashicorp/terraform/terraform" 12 ) 13 14 func TestAccDigitalOceanSSHKey_Basic(t *testing.T) { 15 var key godo.Key 16 rInt := acctest.RandInt() 17 publicKeyMaterial, _, err := acctest.RandSSHKeyPair("digitalocean@ssh-acceptance-test") 18 if err != nil { 19 t.Fatalf("Cannot generate test SSH key pair: %s", err) 20 } 21 22 resource.Test(t, resource.TestCase{ 23 PreCheck: func() { testAccPreCheck(t) }, 24 Providers: testAccProviders, 25 CheckDestroy: testAccCheckDigitalOceanSSHKeyDestroy, 26 Steps: []resource.TestStep{ 27 { 28 Config: testAccCheckDigitalOceanSSHKeyConfig_basic(rInt, publicKeyMaterial), 29 Check: resource.ComposeTestCheckFunc( 30 testAccCheckDigitalOceanSSHKeyExists("digitalocean_ssh_key.foobar", &key), 31 resource.TestCheckResourceAttr( 32 "digitalocean_ssh_key.foobar", "name", fmt.Sprintf("foobar-%d", rInt)), 33 resource.TestCheckResourceAttr( 34 "digitalocean_ssh_key.foobar", "public_key", publicKeyMaterial), 35 ), 36 }, 37 }, 38 }) 39 } 40 41 func testAccCheckDigitalOceanSSHKeyDestroy(s *terraform.State) error { 42 client := testAccProvider.Meta().(*godo.Client) 43 44 for _, rs := range s.RootModule().Resources { 45 if rs.Type != "digitalocean_ssh_key" { 46 continue 47 } 48 49 id, err := strconv.Atoi(rs.Primary.ID) 50 if err != nil { 51 return err 52 } 53 54 // Try to find the key 55 _, _, err = client.Keys.GetByID(id) 56 57 if err == nil { 58 return fmt.Errorf("SSH key still exists") 59 } 60 } 61 62 return nil 63 } 64 65 func testAccCheckDigitalOceanSSHKeyExists(n string, key *godo.Key) resource.TestCheckFunc { 66 return func(s *terraform.State) error { 67 rs, ok := s.RootModule().Resources[n] 68 69 if !ok { 70 return fmt.Errorf("Not found: %s", n) 71 } 72 73 if rs.Primary.ID == "" { 74 return fmt.Errorf("No Record ID is set") 75 } 76 77 client := testAccProvider.Meta().(*godo.Client) 78 79 id, err := strconv.Atoi(rs.Primary.ID) 80 if err != nil { 81 return err 82 } 83 84 // Try to find the key 85 foundKey, _, err := client.Keys.GetByID(id) 86 87 if err != nil { 88 return err 89 } 90 91 if strconv.Itoa(foundKey.ID) != rs.Primary.ID { 92 return fmt.Errorf("Record not found") 93 } 94 95 *key = *foundKey 96 97 return nil 98 } 99 } 100 101 func testAccCheckDigitalOceanSSHKeyConfig_basic(rInt int, key string) string { 102 return fmt.Sprintf(` 103 resource "digitalocean_ssh_key" "foobar" { 104 name = "foobar-%d" 105 public_key = "%s" 106 }`, rInt, key) 107 }