github.com/ezbercih/terraform@v0.1.1-0.20140729011846-3c33865e0839/builtin/providers/aws/resource_aws_subnet_test.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/hashicorp/terraform/helper/resource" 8 "github.com/hashicorp/terraform/terraform" 9 "github.com/mitchellh/goamz/ec2" 10 ) 11 12 func TestAccAWSSubnet(t *testing.T) { 13 var v ec2.Subnet 14 15 testCheck := func(*terraform.State) error { 16 if v.CidrBlock != "10.1.1.0/24" { 17 return fmt.Errorf("bad cidr: %s", v.CidrBlock) 18 } 19 20 return nil 21 } 22 23 resource.Test(t, resource.TestCase{ 24 PreCheck: func() { testAccPreCheck(t) }, 25 Providers: testAccProviders, 26 CheckDestroy: testAccCheckSubnetDestroy, 27 Steps: []resource.TestStep{ 28 resource.TestStep{ 29 Config: testAccSubnetConfig, 30 Check: resource.ComposeTestCheckFunc( 31 testAccCheckSubnetExists( 32 "aws_subnet.foo", &v), 33 testCheck, 34 ), 35 }, 36 }, 37 }) 38 } 39 40 func testAccCheckSubnetDestroy(s *terraform.State) error { 41 conn := testAccProvider.ec2conn 42 43 for _, rs := range s.Resources { 44 if rs.Type != "aws_subnet" { 45 continue 46 } 47 48 // Try to find the resource 49 resp, err := conn.DescribeSubnets( 50 []string{rs.ID}, ec2.NewFilter()) 51 if err == nil { 52 if len(resp.Subnets) > 0 { 53 return fmt.Errorf("still exist.") 54 } 55 56 return nil 57 } 58 59 // Verify the error is what we want 60 ec2err, ok := err.(*ec2.Error) 61 if !ok { 62 return err 63 } 64 if ec2err.Code != "InvalidSubnetID.NotFound" { 65 return err 66 } 67 } 68 69 return nil 70 } 71 72 func testAccCheckSubnetExists(n string, v *ec2.Subnet) resource.TestCheckFunc { 73 return func(s *terraform.State) error { 74 rs, ok := s.Resources[n] 75 if !ok { 76 return fmt.Errorf("Not found: %s", n) 77 } 78 79 if rs.ID == "" { 80 return fmt.Errorf("No ID is set") 81 } 82 83 conn := testAccProvider.ec2conn 84 resp, err := conn.DescribeSubnets( 85 []string{rs.ID}, ec2.NewFilter()) 86 if err != nil { 87 return err 88 } 89 if len(resp.Subnets) == 0 { 90 return fmt.Errorf("Subnet not found") 91 } 92 93 *v = resp.Subnets[0] 94 95 return nil 96 } 97 } 98 99 const testAccSubnetConfig = ` 100 resource "aws_vpc" "foo" { 101 cidr_block = "10.1.0.0/16" 102 } 103 104 resource "aws_subnet" "foo" { 105 cidr_block = "10.1.1.0/24" 106 vpc_id = "${aws_vpc.foo.id}" 107 } 108 `