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