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