<commit_before>package aws

import (
	"fmt"
	"os"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSRouteTable_basic(t *testing.T) {
	var v ec2.RouteTable

	testCheck := func(*terraform.State) error {
		if len(v.Routes) != 2 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.2.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}

	testCheckChange := func(*terraform.State) error {
		if len(v.Routes) != 3 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.3.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.4.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheck,
				),
			},

			resource.TestStep{
				Config: testAccRouteTableConfigChange,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheckChange,
				),
			},
		},
	})
}

func TestAccAWSRouteTable_instance(t *testing.T) {
	var v ec2.RouteTable

	testCheck := func(*terraform.State) error {
		if len(v.Routes) != 2 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.2.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableConfigInstance,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheck,
				),
			},
		},
	})
}

func TestAccAWSRouteTable_tags(t *testing.T) {
	var route_table ec2.RouteTable

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableConfigTags,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists("aws_route_table.foo", &route_table),
					testAccCheckTags(&route_table.Tags, "foo", "bar"),
				),
			},

			resource.TestStep{
				Config: testAccRouteTableConfigTagsUpdate,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists("aws_route_table.foo", &route_table),
					testAccCheckTags(&route_table.Tags, "foo", ""),
					testAccCheckTags(&route_table.Tags, "bar", "baz"),
				),
			},
		},
	})
}

func testAccCheckRouteTableDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).ec2conn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_route_table" {
			continue
		}

		// Try to find the resource
		resp, err := conn.DescribeRouteTables(&ec2.DescribeRouteTablesInput{
			RouteTableIds: []*string{aws.String(rs.Primary.ID)},
		})
		if err == nil {
			if len(resp.RouteTables) > 0 {
				return fmt.Errorf("still exist.")
			}

			return nil
		}

		// Verify the error is what we want
		ec2err, ok := err.(awserr.Error)
		if !ok {
			return err
		}
		if ec2err.Code() != "InvalidRouteTableID.NotFound" {
			return err
		}
	}

	return nil
}

func testAccCheckRouteTableExists(n string, v *ec2.RouteTable) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).ec2conn
		resp, err := conn.DescribeRouteTables(&ec2.DescribeRouteTablesInput{
			RouteTableIds: []*string{aws.String(rs.Primary.ID)},
		})
		if err != nil {
			return err
		}
		if len(resp.RouteTables) == 0 {
			return fmt.Errorf("RouteTable not found")
		}

		*v = *resp.RouteTables[0]

		return nil
	}
}

// VPC Peering connections are prefixed with pcx
// Right now there is no VPC Peering resource
func TestAccAWSRouteTable_vpcPeering(t *testing.T) {
	var v ec2.RouteTable

	acctId := os.Getenv("TF_ACC_ID")
	if acctId == "" && os.Getenv(resource.TestEnvVar) != "" {
		t.Fatal("Error: Test TestAccAWSRouteTable_vpcPeering requires an Account ID in TF_ACC_ID ")
	}

	testCheck := func(*terraform.State) error {
		if len(v.Routes) != 2 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.2.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}
	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableVpcPeeringConfig(acctId),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheck,
				),
			},
		},
	})
}

func TestAccAWSRouteTable_vgwRoutePropagation(t *testing.T) {
	var v ec2.RouteTable
	var vgw ec2.VpnGateway

	testCheck := func(*terraform.State) error {
		if len(v.PropagatingVgws) != 1 {
			return fmt.Errorf("bad propagating vgws: %#v", v.PropagatingVgws)
		}

		propagatingVGWs := make(map[string]*ec2.PropagatingVgw)
		for _, gw := range v.PropagatingVgws {
			propagatingVGWs[*gw.GatewayId] = gw
		}

		if _, ok := propagatingVGWs[*vgw.VpnGatewayId]; !ok {
			return fmt.Errorf("bad propagating vgws: %#v", v.PropagatingVgws)
		}

		return nil

	}
	resource.Test(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		CheckDestroy: resource.ComposeTestCheckFunc(
			testAccCheckVpnGatewayDestroy,
			testAccCheckRouteTableDestroy,
		),
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableVgwRoutePropagationConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testAccCheckVpnGatewayExists(
						"aws_vpn_gateway.foo", &vgw),
					testCheck,
				),
			},
		},
	})
}

const testAccRouteTableConfig = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_internet_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.2.0.0/16"
		gateway_id = "${aws_internet_gateway.foo.id}"
	}
}
`

const testAccRouteTableConfigChange = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_internet_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.3.0.0/16"
		gateway_id = "${aws_internet_gateway.foo.id}"
	}

	route {
		cidr_block = "10.4.0.0/16"
		gateway_id = "${aws_internet_gateway.foo.id}"
	}
}
`

const testAccRouteTableConfigInstance = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_subnet" "foo" {
	cidr_block = "10.1.1.0/24"
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_instance" "foo" {
	# us-west-2
	ami = "ami-4fccb37f"
	instance_type = "m1.small"
	subnet_id = "${aws_subnet.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.2.0.0/16"
		instance_id = "${aws_instance.foo.id}"
	}
}
`

const testAccRouteTableConfigTags = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	tags {
		foo = "bar"
	}
}
`

const testAccRouteTableConfigTagsUpdate = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	tags {
		bar = "baz"
	}
}
`

// VPC Peering connections are prefixed with pcx
// This test requires an ENV var, TF_ACC_ID, with a valid AWS Account ID
func testAccRouteTableVpcPeeringConfig(acc string) string {
	cfg := `resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_internet_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_vpc" "bar" {
	cidr_block = "10.3.0.0/16"
}

resource "aws_internet_gateway" "bar" {
	vpc_id = "${aws_vpc.bar.id}"
}

resource "aws_vpc_peering_connection" "foo" {
		vpc_id = "${aws_vpc.foo.id}"
		peer_vpc_id = "${aws_vpc.bar.id}"
		peer_owner_id = "%s"
		tags {
			foo = "bar"
		}
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.2.0.0/16"
		vpc_peering_connection_id = "${aws_vpc_peering_connection.foo.id}"
	}
}
`
	return fmt.Sprintf(cfg, acc)
}

const testAccRouteTableVgwRoutePropagationConfig = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_vpn_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	propagating_vgws = ["${aws_vpn_gateway.foo.id}"]
}
`
<commit_msg>provider/aws: route table test; use standard account id env var<commit_after>package aws

import (
	"fmt"
	"os"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSRouteTable_basic(t *testing.T) {
	var v ec2.RouteTable

	testCheck := func(*terraform.State) error {
		if len(v.Routes) != 2 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.2.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}

	testCheckChange := func(*terraform.State) error {
		if len(v.Routes) != 3 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.3.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.4.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheck,
				),
			},

			resource.TestStep{
				Config: testAccRouteTableConfigChange,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheckChange,
				),
			},
		},
	})
}

func TestAccAWSRouteTable_instance(t *testing.T) {
	var v ec2.RouteTable

	testCheck := func(*terraform.State) error {
		if len(v.Routes) != 2 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.2.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableConfigInstance,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheck,
				),
			},
		},
	})
}

func TestAccAWSRouteTable_tags(t *testing.T) {
	var route_table ec2.RouteTable

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableConfigTags,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists("aws_route_table.foo", &route_table),
					testAccCheckTags(&route_table.Tags, "foo", "bar"),
				),
			},

			resource.TestStep{
				Config: testAccRouteTableConfigTagsUpdate,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists("aws_route_table.foo", &route_table),
					testAccCheckTags(&route_table.Tags, "foo", ""),
					testAccCheckTags(&route_table.Tags, "bar", "baz"),
				),
			},
		},
	})
}

func testAccCheckRouteTableDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).ec2conn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_route_table" {
			continue
		}

		// Try to find the resource
		resp, err := conn.DescribeRouteTables(&ec2.DescribeRouteTablesInput{
			RouteTableIds: []*string{aws.String(rs.Primary.ID)},
		})
		if err == nil {
			if len(resp.RouteTables) > 0 {
				return fmt.Errorf("still exist.")
			}

			return nil
		}

		// Verify the error is what we want
		ec2err, ok := err.(awserr.Error)
		if !ok {
			return err
		}
		if ec2err.Code() != "InvalidRouteTableID.NotFound" {
			return err
		}
	}

	return nil
}

func testAccCheckRouteTableExists(n string, v *ec2.RouteTable) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).ec2conn
		resp, err := conn.DescribeRouteTables(&ec2.DescribeRouteTablesInput{
			RouteTableIds: []*string{aws.String(rs.Primary.ID)},
		})
		if err != nil {
			return err
		}
		if len(resp.RouteTables) == 0 {
			return fmt.Errorf("RouteTable not found")
		}

		*v = *resp.RouteTables[0]

		return nil
	}
}

// VPC Peering connections are prefixed with pcx
// Right now there is no VPC Peering resource
func TestAccAWSRouteTable_vpcPeering(t *testing.T) {
	var v ec2.RouteTable

	testCheck := func(*terraform.State) error {
		if len(v.Routes) != 2 {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		routes := make(map[string]*ec2.Route)
		for _, r := range v.Routes {
			routes[*r.DestinationCidrBlock] = r
		}

		if _, ok := routes["10.1.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}
		if _, ok := routes["10.2.0.0/16"]; !ok {
			return fmt.Errorf("bad routes: %#v", v.Routes)
		}

		return nil
	}
	resource.Test(t, resource.TestCase{
		PreCheck: func() {
			testAccPreCheck(t)
			if os.Getenv("AWS_ACCOUNT_ID") == "" {
				t.Fatal("Error: Test TestAccAWSRouteTable_vpcPeering requires an Account ID in AWS_ACCOUNT_ID ")
			}
		},
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckRouteTableDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableVpcPeeringConfig(os.Getenv("AWS_ACCOUNT_ID")),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testCheck,
				),
			},
		},
	})
}

func TestAccAWSRouteTable_vgwRoutePropagation(t *testing.T) {
	var v ec2.RouteTable
	var vgw ec2.VpnGateway

	testCheck := func(*terraform.State) error {
		if len(v.PropagatingVgws) != 1 {
			return fmt.Errorf("bad propagating vgws: %#v", v.PropagatingVgws)
		}

		propagatingVGWs := make(map[string]*ec2.PropagatingVgw)
		for _, gw := range v.PropagatingVgws {
			propagatingVGWs[*gw.GatewayId] = gw
		}

		if _, ok := propagatingVGWs[*vgw.VpnGatewayId]; !ok {
			return fmt.Errorf("bad propagating vgws: %#v", v.PropagatingVgws)
		}

		return nil

	}
	resource.Test(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		CheckDestroy: resource.ComposeTestCheckFunc(
			testAccCheckVpnGatewayDestroy,
			testAccCheckRouteTableDestroy,
		),
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccRouteTableVgwRoutePropagationConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckRouteTableExists(
						"aws_route_table.foo", &v),
					testAccCheckVpnGatewayExists(
						"aws_vpn_gateway.foo", &vgw),
					testCheck,
				),
			},
		},
	})
}

const testAccRouteTableConfig = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_internet_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.2.0.0/16"
		gateway_id = "${aws_internet_gateway.foo.id}"
	}
}
`

const testAccRouteTableConfigChange = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_internet_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.3.0.0/16"
		gateway_id = "${aws_internet_gateway.foo.id}"
	}

	route {
		cidr_block = "10.4.0.0/16"
		gateway_id = "${aws_internet_gateway.foo.id}"
	}
}
`

const testAccRouteTableConfigInstance = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_subnet" "foo" {
	cidr_block = "10.1.1.0/24"
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_instance" "foo" {
	# us-west-2
	ami = "ami-4fccb37f"
	instance_type = "m1.small"
	subnet_id = "${aws_subnet.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.2.0.0/16"
		instance_id = "${aws_instance.foo.id}"
	}
}
`

const testAccRouteTableConfigTags = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	tags {
		foo = "bar"
	}
}
`

const testAccRouteTableConfigTagsUpdate = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	tags {
		bar = "baz"
	}
}
`

// VPC Peering connections are prefixed with pcx
// This test requires an ENV var, AWS_ACCOUNT_ID, with a valid AWS Account ID
func testAccRouteTableVpcPeeringConfig(acc string) string {
	cfg := `resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_internet_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_vpc" "bar" {
	cidr_block = "10.3.0.0/16"
}

resource "aws_internet_gateway" "bar" {
	vpc_id = "${aws_vpc.bar.id}"
}

resource "aws_vpc_peering_connection" "foo" {
		vpc_id = "${aws_vpc.foo.id}"
		peer_vpc_id = "${aws_vpc.bar.id}"
		peer_owner_id = "%s"
		tags {
			foo = "bar"
		}
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	route {
		cidr_block = "10.2.0.0/16"
		vpc_peering_connection_id = "${aws_vpc_peering_connection.foo.id}"
	}
}
`
	return fmt.Sprintf(cfg, acc)
}

const testAccRouteTableVgwRoutePropagationConfig = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_vpn_gateway" "foo" {
	vpc_id = "${aws_vpc.foo.id}"
}

resource "aws_route_table" "foo" {
	vpc_id = "${aws_vpc.foo.id}"

	propagating_vgws = ["${aws_vpn_gateway.foo.id}"]
}
`
<|endoftext|>


<commit_before>package engine_test

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/strslice"
	docker "github.com/docker/docker/client"
	gouuid "github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/sclevine/cflocal/engine"
	"github.com/sclevine/cflocal/ui"
)

var _ = Describe("Image", func() {
	var (
		image  *Image
		client *docker.Client
		ctx    context.Context
	)

	clearImage := func(image string) {
		client.ImageRemove(ctx, image, types.ImageRemoveOptions{
			Force:         true,
			PruneChildren: true,
		})
	}

	BeforeEach(func() {
		var err error
		client, err = docker.NewEnvClient()
		Expect(err).NotTo(HaveOccurred())
		client.UpdateClientVersion("")
		image = &Image{Docker: client}

		ctx = context.Background()
		clearImage("sclevine/test")
	})

	AfterEach(func() {
		clearImage("sclevine/test")
	})

	Describe("#Build", func() {
		var tag string

		BeforeEach(func() {
			uuid, err := gouuid.NewV4()
			Expect(err).NotTo(HaveOccurred())
			tag = fmt.Sprintf("some-image-%s", uuid)
		})

		AfterEach(func() {
			clearImage(tag)
		})

		It("should build a Dockerfile and tag the resulting image", func() {
			dockerfile := bytes.NewBufferString(`
				FROM sclevine/test
				RUN echo some-data > /some-path
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len()))

			progress := image.Build(tag, dockerfileStream)
			naCount := 0
			for p := range progress {
				Expect(p.Err()).NotTo(HaveOccurred())
				if p.Status() == "N/A" {
					naCount++
				} else {
					Expect(p.Status()).To(HaveSuffix("MB"))
				}
			}
			Expect(naCount).To(Equal(14))

			info, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).NotTo(HaveOccurred())
			Expect(info.RepoTags[0]).To(Equal(tag + ":latest"))

			info.Config.Image = tag + ":latest"
			info.Config.Entrypoint = strslice.StrSlice{"bash"}
			contr, err := NewContainer(client, info.Config, nil)
			Expect(err).NotTo(HaveOccurred())
			defer contr.Close()

			outStream, err := contr.CopyFrom("/some-path")
			Expect(err).NotTo(HaveOccurred())
			Expect(ioutil.ReadAll(outStream)).To(Equal([]byte("some-data\n")))
		})

		It("should send an error when the Dockerfile cannot be tarred", func() {
			dockerfile := bytes.NewBufferString(`
				FROM sclevine/test
				RUN echo some-data > /some-path
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len())+100)

			progress := image.Build(tag, dockerfileStream)
			var progressErr ui.Progress
			Expect(progress).To(Receive(&progressErr))
			Expect(progressErr.Err()).To(MatchError("EOF"))
			Expect(progress).To(BeClosed())

			_, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).To(MatchError("Error: No such image: " + tag))
		})

		It("should send an error when the image build request is invalid", func() {
			dockerfile := bytes.NewBufferString(`
				SOME BAD DOCKERFILE
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len()))

			progress := image.Build(tag, dockerfileStream)
			var progressErr ui.Progress
			Expect(progress).To(Receive(&progressErr))
			Expect(progressErr.Err()).To(MatchError(HaveSuffix("Unknown instruction: SOME")))
			Expect(progress).To(BeClosed())

			_, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).To(MatchError("Error: No such image: " + tag))
		})

		It("should send an error when an error occurs during the image build", func() {
			dockerfile := bytes.NewBufferString(`
				FROM sclevine/test
				RUN false
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len()))

			progress := image.Build(tag, dockerfileStream)
			var progressErr ui.Progress
			for progressErr = range progress {
				if progressErr.Err() != nil {
					break
				}
			}
			Expect(progressErr.Err()).To(MatchError(ContainSubstring("non-zero code")))
			Expect(progress).To(BeClosed())

			_, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).To(MatchError("Error: No such image: " + tag))
		})
	})

	Describe("#Pull", func() {
		var ctx context.Context

		BeforeEach(func() {
			ctx = context.Background()
		})

		It("should pull a Docker image", func() {
			progress := image.Pull("sclevine/test")
			naCount := 0
			for p := range progress {
				Expect(p.Err()).NotTo(HaveOccurred())
				if p.Status() == "N/A" {
					naCount++
				} else {
					Expect(p.Status()).To(HaveSuffix("MB"))
				}
			}
			Expect(naCount).To(Equal(7))

			info, _, err := client.ImageInspectWithRaw(ctx, "sclevine/test")
			Expect(err).NotTo(HaveOccurred())
			Expect(info.RepoTags[0]).To(Equal("sclevine/test:latest"))

			info.Config.Image = "sclevine/test:latest"
			info.Config.Entrypoint = strslice.StrSlice{"sh"}
			contr, err := NewContainer(client, info.Config, nil)
			Expect(err).NotTo(HaveOccurred())
			defer contr.Close()

			outStream, err := contr.CopyFrom("/testfile")
			Expect(err).NotTo(HaveOccurred())
			Expect(ioutil.ReadAll(outStream)).To(Equal([]byte("test-data\n")))
		})

		It("should send an error when the image pull request is invalid", func() {
			progress := image.Pull("-----")

			var progressErr ui.Progress
			Expect(progress).To(Receive(&progressErr))
			Expect(progressErr.Err()).To(MatchError(HaveSuffix("invalid reference format")))
			Expect(progress).To(BeClosed())
		})

		It("should send an error when an error occurs during the image build", func() {
			progress := image.Pull("sclevine/bad-test")
			var progressErr ui.Progress
			for progressErr = range progress {
				if progressErr.Err() != nil {
					break
				}
			}
			Expect(progressErr.Err()).To(MatchError(ContainSubstring("repository sclevine/bad-test not found")))
			Expect(progress).To(BeClosed())
		})
	})
})
<commit_msg>Improve engine test reliability<commit_after>package engine_test

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/strslice"
	docker "github.com/docker/docker/client"
	gouuid "github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/sclevine/cflocal/engine"
	"github.com/sclevine/cflocal/ui"
)

var _ = Describe("Image", func() {
	var (
		image  *Image
		client *docker.Client
		ctx    context.Context
	)

	clearImage := func(image string) {
		client.ImageRemove(ctx, image, types.ImageRemoveOptions{
			Force:         true,
			PruneChildren: true,
		})
	}

	BeforeEach(func() {
		var err error
		client, err = docker.NewEnvClient()
		Expect(err).NotTo(HaveOccurred())
		client.UpdateClientVersion("")
		image = &Image{Docker: client}

		ctx = context.Background()
		clearImage("sclevine/test")
	})

	AfterEach(func() {
		clearImage("sclevine/test")
	})

	Describe("#Build", func() {
		var tag string

		BeforeEach(func() {
			uuid, err := gouuid.NewV4()
			Expect(err).NotTo(HaveOccurred())
			tag = fmt.Sprintf("some-image-%s", uuid)
		})

		AfterEach(func() {
			clearImage(tag)
		})

		It("should build a Dockerfile and tag the resulting image", func() {
			dockerfile := bytes.NewBufferString(`
				FROM sclevine/test
				RUN echo some-data > /some-path
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len()))

			progress := image.Build(tag, dockerfileStream)
			naCount := 0
			for p := range progress {
				Expect(p.Err()).NotTo(HaveOccurred())
				if p.Status() == "N/A" {
					naCount++
				} else {
					Expect(p.Status()).To(HaveSuffix("MB"))
				}
			}
			Expect(naCount).To(BeNumerically(">", 10))
			Expect(naCount).To(BeNumerically("<", 30))

			info, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).NotTo(HaveOccurred())
			Expect(info.RepoTags[0]).To(Equal(tag + ":latest"))

			info.Config.Image = tag + ":latest"
			info.Config.Entrypoint = strslice.StrSlice{"bash"}
			contr, err := NewContainer(client, info.Config, nil)
			Expect(err).NotTo(HaveOccurred())
			defer contr.Close()

			outStream, err := contr.CopyFrom("/some-path")
			Expect(err).NotTo(HaveOccurred())
			Expect(ioutil.ReadAll(outStream)).To(Equal([]byte("some-data\n")))
		})

		It("should send an error when the Dockerfile cannot be tarred", func() {
			dockerfile := bytes.NewBufferString(`
				FROM sclevine/test
				RUN echo some-data > /some-path
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len())+100)

			progress := image.Build(tag, dockerfileStream)
			var progressErr ui.Progress
			Eventually(progress).Should(Receive(&progressErr))
			Expect(progressErr.Err()).To(MatchError("EOF"))
			Expect(progress).To(BeClosed())

			_, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).To(MatchError("Error: No such image: " + tag))
		})

		It("should send an error when the image build request is invalid", func() {
			dockerfile := bytes.NewBufferString(`
				SOME BAD DOCKERFILE
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len()))

			progress := image.Build(tag, dockerfileStream)
			var progressErr ui.Progress
			Eventually(progress).Should(Receive(&progressErr))
			Expect(progressErr.Err()).To(MatchError(HaveSuffix("Unknown instruction: SOME")))
			Expect(progress).To(BeClosed())

			_, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).To(MatchError("Error: No such image: " + tag))
		})

		It("should send an error when an error occurs during the image build", func() {
			dockerfile := bytes.NewBufferString(`
				FROM sclevine/test
				RUN false
			`)
			dockerfileStream := NewStream(ioutil.NopCloser(dockerfile), int64(dockerfile.Len()))

			progress := image.Build(tag, dockerfileStream)
			var progressErr ui.Progress
			for progressErr = range progress {
				if progressErr.Err() != nil {
					break
				}
			}
			Expect(progressErr.Err()).To(MatchError(ContainSubstring("non-zero code")))
			Expect(progress).To(BeClosed())

			_, _, err := client.ImageInspectWithRaw(ctx, tag)
			Expect(err).To(MatchError("Error: No such image: " + tag))
		})
	})

	Describe("#Pull", func() {
		var ctx context.Context

		BeforeEach(func() {
			ctx = context.Background()
		})

		It("should pull a Docker image", func() {
			progress := image.Pull("sclevine/test")
			naCount := 0
			for p := range progress {
				Expect(p.Err()).NotTo(HaveOccurred())
				if p.Status() == "N/A" {
					naCount++
				} else {
					Expect(p.Status()).To(HaveSuffix("MB"))
				}
			}
			Expect(naCount).To(BeNumerically(">", 0))
			Expect(naCount).To(BeNumerically("<", 20))

			info, _, err := client.ImageInspectWithRaw(ctx, "sclevine/test")
			Expect(err).NotTo(HaveOccurred())
			Expect(info.RepoTags[0]).To(Equal("sclevine/test:latest"))

			info.Config.Image = "sclevine/test:latest"
			info.Config.Entrypoint = strslice.StrSlice{"sh"}
			contr, err := NewContainer(client, info.Config, nil)
			Expect(err).NotTo(HaveOccurred())
			defer contr.Close()

			outStream, err := contr.CopyFrom("/testfile")
			Expect(err).NotTo(HaveOccurred())
			Expect(ioutil.ReadAll(outStream)).To(Equal([]byte("test-data\n")))
		})

		It("should send an error when the image pull request is invalid", func() {
			progress := image.Pull("-----")

			var progressErr ui.Progress
			Expect(progress).To(Receive(&progressErr))
			Expect(progressErr.Err()).To(MatchError(HaveSuffix("invalid reference format")))
			Expect(progress).To(BeClosed())
		})

		It("should send an error when an error occurs during the image build", func() {
			progress := image.Pull("sclevine/bad-test")
			var progressErr ui.Progress
			for progressErr = range progress {
				if progressErr.Err() != nil {
					break
				}
			}
			Expect(progressErr.Err()).To(MatchError(ContainSubstring("not found")))
			Expect(progress).To(BeClosed())
		})
	})
})
<|endoftext|>


<commit_before>package wrp

import (
	"bytes"
	"errors"
	"fmt"
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestSampleMsgpack(t *testing.T) {
	var (
		sampleEncoded = []byte{
			0x85, 0xa8, 0x6d, 0x73, 0x67, 0x5f, 0x74, 0x79,
			0x70, 0x65, 0x03, 0xb0, 0x74, 0x72, 0x61, 0x6e,
			0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f,
			0x75, 0x75, 0x69, 0x64, 0xd9, 0x24, 0x39, 0x34,
			0x34, 0x37, 0x32, 0x34, 0x31, 0x63, 0x2d, 0x35,
			0x32, 0x33, 0x38, 0x2d, 0x34, 0x63, 0x62, 0x39,
			0x2d, 0x39, 0x62, 0x61, 0x61, 0x2d, 0x37, 0x30,
			0x37, 0x36, 0x65, 0x33, 0x32, 0x33, 0x32, 0x38,
			0x39, 0x39, 0xa6, 0x73, 0x6f, 0x75, 0x72, 0x63,
			0x65, 0xd9, 0x26, 0x64, 0x6e, 0x73, 0x3a, 0x77,
			0x65, 0x62, 0x70, 0x61, 0x2e, 0x63, 0x6f, 0x6d,
			0x63, 0x61, 0x73, 0x74, 0x2e, 0x63, 0x6f, 0x6d,
			0x2f, 0x76, 0x32, 0x2d, 0x64, 0x65, 0x76, 0x69,
			0x63, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x66, 0x69,
			0x67, 0xa4, 0x64, 0x65, 0x73, 0x74, 0xb2, 0x73,
			0x65, 0x72, 0x69, 0x61, 0x6c, 0x3a, 0x31, 0x32,
			0x33, 0x34, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69,
			0x67, 0xa7, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61,
			0x64, 0xc4, 0x45, 0x7b, 0x20, 0x22, 0x6e, 0x61,
			0x6d, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x5b, 0x20,
			0x22, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2e,
			0x58, 0x5f, 0x43, 0x49, 0x53, 0x43, 0x4f, 0x5f,
			0x43, 0x4f, 0x4d, 0x5f, 0x53, 0x65, 0x63, 0x75,
			0x72, 0x69, 0x74, 0x79, 0x2e, 0x46, 0x69, 0x72,
			0x65, 0x77, 0x61, 0x6c, 0x6c, 0x2e, 0x46, 0x69,
			0x72, 0x65, 0x77, 0x61, 0x6c, 0x6c, 0x4c, 0x65,
			0x76, 0x65, 0x6c, 0x22, 0x20, 0x5d, 0x20, 0x7d,
		}

		sampleMessage = SimpleRequestResponse{
			Type:            SimpleRequestResponseMessageType,
			Source:          "dns:webpa.comcast.com/v2-device-config",
			Destination:     "serial:1234/config",
			TransactionUUID: "9447241c-5238-4cb9-9baa-7076e3232899",
			Payload: []byte(
				`{ "names": [ "Device.X_CISCO_COM_Security.Firewall.FirewallLevel" ] }`,
			),
		}
	)

	t.Run("Encode", func(t *testing.T) {
		var (
			assert        = assert.New(t)
			buffer        bytes.Buffer
			encoder       = NewEncoder(&buffer, Msgpack)
			decoder       = NewDecoder(&buffer, Msgpack)
			actualMessage SimpleRequestResponse
		)

		assert.NoError(encoder.Encode(&sampleMessage))
		assert.NoError(decoder.Decode(&actualMessage))
		assert.Equal(sampleMessage, actualMessage)
	})

	t.Run("Decode", func(t *testing.T) {
		var (
			assert        = assert.New(t)
			decoder       = NewDecoder(bytes.NewBuffer(sampleEncoded), Msgpack)
			actualMessage SimpleRequestResponse
		)

		assert.NoError(decoder.Decode(&actualMessage))
		assert.Equal(sampleMessage, actualMessage)
	})

	t.Run("DecodeBytes", func(t *testing.T) {
		var (
			assert        = assert.New(t)
			decoder       = NewDecoderBytes(sampleEncoded, Msgpack)
			actualMessage SimpleRequestResponse
		)

		assert.NoError(decoder.Decode(&actualMessage))
		assert.Equal(sampleMessage, actualMessage)
	})
}

func testFormatString(t *testing.T) {
	assert := assert.New(t)

	assert.NotEmpty(JSON.String())
	assert.NotEmpty(Msgpack.String())
	assert.NotEmpty(Format(-1).String())
	assert.NotEqual(JSON.String(), Msgpack.String())
}

func testFormatHandle(t *testing.T) {
	assert := assert.New(t)

	assert.NotNil(JSON.handle())
	assert.NotNil(Msgpack.handle())
	assert.Panics(func() { Format(999).handle() })
}

func testFormatContentType(t *testing.T) {
	assert := assert.New(t)

	assert.NotEmpty(JSON.ContentType())
	assert.NotEmpty(Msgpack.ContentType())
	assert.NotEqual(JSON.ContentType(), Msgpack.ContentType())
	assert.Equal("application/octet-stream", Format(999).ContentType())
}

func testFormatFromContentType(t *testing.T) {
	var (
		assert   = assert.New(t)
		testData = []struct {
			contentType  string
			expected     Format
			expectsError bool
		}{
			{"application/json", JSON, false},
			{"application/json;charset=utf-8", JSON, false},
			{"application/msgpack", Msgpack, false},
			{"text/plain", Format(-1), true},
		}
	)

	for _, record := range testData {
		t.Logf("%#v", record)
		actual, err := FormatFromContentType(record.contentType)
		assert.Equal(record.expected, actual)
		assert.Equal(record.expectsError, err != nil)
	}
}

func TestFormat(t *testing.T) {
	t.Run("String", testFormatString)
	t.Run("Handle", testFormatHandle)
	t.Run("ContentType", testFormatContentType)
	t.Run("FromContentType", testFormatFromContentType)
}

// testTranscodeMessage expects a nonpointer reference to a WRP message struct as the original parameter
func testTranscodeMessage(t *testing.T, target, source Format, original interface{}) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		originalValue = reflect.ValueOf(original)
		encodeValue   = reflect.New(originalValue.Type())
		decodeValue   = reflect.New(originalValue.Type())
	)

	// encodeValue is now a pointer to a copy of the original
	encodeValue.Elem().Set(originalValue)

	var (
		sourceBuffer  bytes.Buffer
		sourceEncoder = NewEncoder(&sourceBuffer, source)
		sourceDecoder = NewDecoder(&sourceBuffer, source)

		targetBuffer  bytes.Buffer
		targetEncoder = NewEncoder(&targetBuffer, target)
		targetDecoder = NewDecoder(&targetBuffer, target)
	)

	// create the input first
	require.NoError(sourceEncoder.Encode(encodeValue.Interface()))

	// now we can attempt the transcode
	message, err := TranscodeMessage(targetEncoder, sourceDecoder)
	assert.NotNil(message)
	assert.NoError(err)

	assert.NoError(targetDecoder.Decode(decodeValue.Interface()))
	assert.Equal(encodeValue.Elem().Interface(), decodeValue.Elem().Interface())
}

func testMustEncodeValid(t *testing.T, f Format) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		message = AuthorizationStatus{Status: AuthStatusAuthorized}

		expectedData bytes.Buffer
		encoder      = NewEncoder(&expectedData, f)
	)

	require.NoError(encoder.Encode(message))

	assert.NotPanics(func() {
		assert.Equal(
			expectedData.Bytes(),
			MustEncode(message, f),
		)
	})
}

func testMustEncodePanic(t *testing.T, f Format) {
	var (
		assert  = assert.New(t)
		message = new(mockEncodeListener)
	)

	message.On("BeforeEncode").Once().Return(errors.New("expected"))

	assert.Panics(func() {
		MustEncode(message, f)
	})

	message.AssertExpectations(t)
}

func TestMustEncode(t *testing.T) {
	for _, f := range []Format{Msgpack, JSON} {
		t.Run(f.String(), func(t *testing.T) {
			t.Run("Valid", func(t *testing.T) { testMustEncodeValid(t, f) })
			t.Run("Panic", func(t *testing.T) { testMustEncodePanic(t, f) })
		})
	}
}

func TestTranscodeMessage(t *testing.T) {
	var (
		expectedStatus                  int64 = 123
		expectedRequestDeliveryResponse int64 = -1234

		messages = []interface{}{
			AuthorizationStatus{},
			AuthorizationStatus{
				Status: expectedStatus,
			},
			SimpleRequestResponse{},
			SimpleRequestResponse{
				Source:      "foobar.com",
				Destination: "mac:FFEEDDCCBBAA",
				Payload:     []byte("hi!"),
			},
			SimpleRequestResponse{
				Source:                  "foobar.com",
				Destination:             "mac:FFEEDDCCBBAA",
				ContentType:             "application/wrp",
				Accept:                  "application/wrp",
				Status:                  &expectedStatus,
				RequestDeliveryResponse: &expectedRequestDeliveryResponse,
				Headers:                 []string{"X-Header-1", "X-Header-2"},
				Metadata:                map[string]string{"hi": "there"},
				Payload:                 []byte("hi!"),
			},
			Message{},
			Message{
				Source:      "foobar.com",
				Destination: "mac:FFEEDDCCBBAA",
				Payload:     []byte("hi!"),
			},
			Message{
				Source:                  "foobar.com",
				Destination:             "mac:FFEEDDCCBBAA",
				ContentType:             "application/wrp",
				Accept:                  "application/wrp",
				Status:                  &expectedStatus,
				RequestDeliveryResponse: &expectedRequestDeliveryResponse,
				Headers:                 []string{"X-Header-1", "X-Header-2"},
				Metadata:                map[string]string{"hi": "there"},
				Payload:                 []byte("hi!"),
			},
		}
	)

	for _, target := range allFormats {
		for _, source := range allFormats {
			t.Run(fmt.Sprintf("%sTo%s", source, target), func(t *testing.T) {
				for _, original := range messages {
					testTranscodeMessage(t, target, source, original)
				}
			})
		}
	}
}
<commit_msg>Added a test for the string-or-binary case<commit_after>package wrp

import (
	"bytes"
	"encoding/hex"
	"errors"
	"fmt"
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestStringOrBinary(t *testing.T) {
	var (
		require  = require.New(t)
		original = Message{
			Payload: []byte("this is clearly a UTF8 string"),
		}

		decoded Message

		output  bytes.Buffer
		encoder = NewEncoder(nil, Msgpack)
		decoder = NewDecoder(nil, Msgpack)
	)

	encoder.Reset(&output)
	require.NoError(encoder.Encode(&original))
	t.Log(hex.Dump(output.Bytes()))

	decoder.Reset(&output)
	require.NoError(decoder.Decode(&decoded))

	t.Logf("original.Payload=%s", original.Payload)
	t.Logf("decoded.Payload=%s", decoded.Payload)
}

func TestSampleMsgpack(t *testing.T) {
	var (
		sampleEncoded = []byte{
			0x85, 0xa8, 0x6d, 0x73, 0x67, 0x5f, 0x74, 0x79,
			0x70, 0x65, 0x03, 0xb0, 0x74, 0x72, 0x61, 0x6e,
			0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f,
			0x75, 0x75, 0x69, 0x64, 0xd9, 0x24, 0x39, 0x34,
			0x34, 0x37, 0x32, 0x34, 0x31, 0x63, 0x2d, 0x35,
			0x32, 0x33, 0x38, 0x2d, 0x34, 0x63, 0x62, 0x39,
			0x2d, 0x39, 0x62, 0x61, 0x61, 0x2d, 0x37, 0x30,
			0x37, 0x36, 0x65, 0x33, 0x32, 0x33, 0x32, 0x38,
			0x39, 0x39, 0xa6, 0x73, 0x6f, 0x75, 0x72, 0x63,
			0x65, 0xd9, 0x26, 0x64, 0x6e, 0x73, 0x3a, 0x77,
			0x65, 0x62, 0x70, 0x61, 0x2e, 0x63, 0x6f, 0x6d,
			0x63, 0x61, 0x73, 0x74, 0x2e, 0x63, 0x6f, 0x6d,
			0x2f, 0x76, 0x32, 0x2d, 0x64, 0x65, 0x76, 0x69,
			0x63, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x66, 0x69,
			0x67, 0xa4, 0x64, 0x65, 0x73, 0x74, 0xb2, 0x73,
			0x65, 0x72, 0x69, 0x61, 0x6c, 0x3a, 0x31, 0x32,
			0x33, 0x34, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69,
			0x67, 0xa7, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61,
			0x64, 0xc4, 0x45, 0x7b, 0x20, 0x22, 0x6e, 0x61,
			0x6d, 0x65, 0x73, 0x22, 0x3a, 0x20, 0x5b, 0x20,
			0x22, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2e,
			0x58, 0x5f, 0x43, 0x49, 0x53, 0x43, 0x4f, 0x5f,
			0x43, 0x4f, 0x4d, 0x5f, 0x53, 0x65, 0x63, 0x75,
			0x72, 0x69, 0x74, 0x79, 0x2e, 0x46, 0x69, 0x72,
			0x65, 0x77, 0x61, 0x6c, 0x6c, 0x2e, 0x46, 0x69,
			0x72, 0x65, 0x77, 0x61, 0x6c, 0x6c, 0x4c, 0x65,
			0x76, 0x65, 0x6c, 0x22, 0x20, 0x5d, 0x20, 0x7d,
		}

		sampleMessage = SimpleRequestResponse{
			Type:            SimpleRequestResponseMessageType,
			Source:          "dns:webpa.comcast.com/v2-device-config",
			Destination:     "serial:1234/config",
			TransactionUUID: "9447241c-5238-4cb9-9baa-7076e3232899",
			Payload: []byte(
				`{ "names": [ "Device.X_CISCO_COM_Security.Firewall.FirewallLevel" ] }`,
			),
		}
	)

	t.Run("Encode", func(t *testing.T) {
		var (
			assert        = assert.New(t)
			buffer        bytes.Buffer
			encoder       = NewEncoder(&buffer, Msgpack)
			decoder       = NewDecoder(&buffer, Msgpack)
			actualMessage SimpleRequestResponse
		)

		assert.NoError(encoder.Encode(&sampleMessage))
		assert.NoError(decoder.Decode(&actualMessage))
		assert.Equal(sampleMessage, actualMessage)
	})

	t.Run("Decode", func(t *testing.T) {
		var (
			assert        = assert.New(t)
			decoder       = NewDecoder(bytes.NewBuffer(sampleEncoded), Msgpack)
			actualMessage SimpleRequestResponse
		)

		assert.NoError(decoder.Decode(&actualMessage))
		assert.Equal(sampleMessage, actualMessage)
	})

	t.Run("DecodeBytes", func(t *testing.T) {
		var (
			assert        = assert.New(t)
			decoder       = NewDecoderBytes(sampleEncoded, Msgpack)
			actualMessage SimpleRequestResponse
		)

		assert.NoError(decoder.Decode(&actualMessage))
		assert.Equal(sampleMessage, actualMessage)
	})
}

func testFormatString(t *testing.T) {
	assert := assert.New(t)

	assert.NotEmpty(JSON.String())
	assert.NotEmpty(Msgpack.String())
	assert.NotEmpty(Format(-1).String())
	assert.NotEqual(JSON.String(), Msgpack.String())
}

func testFormatHandle(t *testing.T) {
	assert := assert.New(t)

	assert.NotNil(JSON.handle())
	assert.NotNil(Msgpack.handle())
	assert.Panics(func() { Format(999).handle() })
}

func testFormatContentType(t *testing.T) {
	assert := assert.New(t)

	assert.NotEmpty(JSON.ContentType())
	assert.NotEmpty(Msgpack.ContentType())
	assert.NotEqual(JSON.ContentType(), Msgpack.ContentType())
	assert.Equal("application/octet-stream", Format(999).ContentType())
}

func testFormatFromContentType(t *testing.T) {
	var (
		assert   = assert.New(t)
		testData = []struct {
			contentType  string
			expected     Format
			expectsError bool
		}{
			{"application/json", JSON, false},
			{"application/json;charset=utf-8", JSON, false},
			{"application/msgpack", Msgpack, false},
			{"text/plain", Format(-1), true},
		}
	)

	for _, record := range testData {
		t.Logf("%#v", record)
		actual, err := FormatFromContentType(record.contentType)
		assert.Equal(record.expected, actual)
		assert.Equal(record.expectsError, err != nil)
	}
}

func TestFormat(t *testing.T) {
	t.Run("String", testFormatString)
	t.Run("Handle", testFormatHandle)
	t.Run("ContentType", testFormatContentType)
	t.Run("FromContentType", testFormatFromContentType)
}

// testTranscodeMessage expects a nonpointer reference to a WRP message struct as the original parameter
func testTranscodeMessage(t *testing.T, target, source Format, original interface{}) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		originalValue = reflect.ValueOf(original)
		encodeValue   = reflect.New(originalValue.Type())
		decodeValue   = reflect.New(originalValue.Type())
	)

	// encodeValue is now a pointer to a copy of the original
	encodeValue.Elem().Set(originalValue)

	var (
		sourceBuffer  bytes.Buffer
		sourceEncoder = NewEncoder(&sourceBuffer, source)
		sourceDecoder = NewDecoder(&sourceBuffer, source)

		targetBuffer  bytes.Buffer
		targetEncoder = NewEncoder(&targetBuffer, target)
		targetDecoder = NewDecoder(&targetBuffer, target)
	)

	// create the input first
	require.NoError(sourceEncoder.Encode(encodeValue.Interface()))

	// now we can attempt the transcode
	message, err := TranscodeMessage(targetEncoder, sourceDecoder)
	assert.NotNil(message)
	assert.NoError(err)

	assert.NoError(targetDecoder.Decode(decodeValue.Interface()))
	assert.Equal(encodeValue.Elem().Interface(), decodeValue.Elem().Interface())
}

func testMustEncodeValid(t *testing.T, f Format) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		message = AuthorizationStatus{Status: AuthStatusAuthorized}

		expectedData bytes.Buffer
		encoder      = NewEncoder(&expectedData, f)
	)

	require.NoError(encoder.Encode(message))

	assert.NotPanics(func() {
		assert.Equal(
			expectedData.Bytes(),
			MustEncode(message, f),
		)
	})
}

func testMustEncodePanic(t *testing.T, f Format) {
	var (
		assert  = assert.New(t)
		message = new(mockEncodeListener)
	)

	message.On("BeforeEncode").Once().Return(errors.New("expected"))

	assert.Panics(func() {
		MustEncode(message, f)
	})

	message.AssertExpectations(t)
}

func TestMustEncode(t *testing.T) {
	for _, f := range []Format{Msgpack, JSON} {
		t.Run(f.String(), func(t *testing.T) {
			t.Run("Valid", func(t *testing.T) { testMustEncodeValid(t, f) })
			t.Run("Panic", func(t *testing.T) { testMustEncodePanic(t, f) })
		})
	}
}

func TestTranscodeMessage(t *testing.T) {
	var (
		expectedStatus                  int64 = 123
		expectedRequestDeliveryResponse int64 = -1234

		messages = []interface{}{
			AuthorizationStatus{},
			AuthorizationStatus{
				Status: expectedStatus,
			},
			SimpleRequestResponse{},
			SimpleRequestResponse{
				Source:      "foobar.com",
				Destination: "mac:FFEEDDCCBBAA",
				Payload:     []byte("hi!"),
			},
			SimpleRequestResponse{
				Source:                  "foobar.com",
				Destination:             "mac:FFEEDDCCBBAA",
				ContentType:             "application/wrp",
				Accept:                  "application/wrp",
				Status:                  &expectedStatus,
				RequestDeliveryResponse: &expectedRequestDeliveryResponse,
				Headers:                 []string{"X-Header-1", "X-Header-2"},
				Metadata:                map[string]string{"hi": "there"},
				Payload:                 []byte("hi!"),
			},
			Message{},
			Message{
				Source:      "foobar.com",
				Destination: "mac:FFEEDDCCBBAA",
				Payload:     []byte("hi!"),
			},
			Message{
				Source:                  "foobar.com",
				Destination:             "mac:FFEEDDCCBBAA",
				ContentType:             "application/wrp",
				Accept:                  "application/wrp",
				Status:                  &expectedStatus,
				RequestDeliveryResponse: &expectedRequestDeliveryResponse,
				Headers:                 []string{"X-Header-1", "X-Header-2"},
				Metadata:                map[string]string{"hi": "there"},
				Payload:                 []byte("hi!"),
			},
		}
	)

	for _, target := range allFormats {
		for _, source := range allFormats {
			t.Run(fmt.Sprintf("%sTo%s", source, target), func(t *testing.T) {
				for _, original := range messages {
					testTranscodeMessage(t, target, source, original)
				}
			})
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/appleboy/drone-facebook/template"
)

type (
	// Repo information
	Repo struct {
		Owner string
		Name  string
	}

	// Build information
	Build struct {
		Tag      string
		Event    string
		Number   int
		Commit   string
		Branch   string
		Author   string
		Avatar   string
		Message  string
		Email    string
		Status   string
		Link     string
		Started  float64
		Finished float64
	}

	// Config for the plugin.
	Config struct {
		WebhookID    string
		WebhookToken string
		Color        string
		Message      []string
		Drone        bool
	}

	// EmbedFooterObject for Embed Footer Structure.
	EmbedFooterObject struct {
		Text    string `json:"text"`
		IconURL string `json:"icon_url"`
	}

	// EmbedAuthorObject for Embed Author Structure
	EmbedAuthorObject struct {
		Name    string `json:"name"`
		URL     string `json:"url"`
		IconURL string `json:"icon_url"`
	}

	// EmbedFieldObject for Embed Field Structure
	EmbedFieldObject struct {
		Name  string `json:"name"`
		Value string `json:"value"`
	}

	// EmbedObject is for Embed Structure
	EmbedObject struct {
		Title       string             `json:"title"`
		Description string             `json:"description"`
		URL         string             `json:"url"`
		Color       int                `json:"color"`
		Footer      EmbedFooterObject  `json:"footer"`
		Author      EmbedAuthorObject  `json:"author"`
		Fields      []EmbedFieldObject `json:"fields"`
	}

	// Payload struct
	Payload struct {
		Wait      bool          `json:"wait"`
		Content   string        `json:"content"`
		Username  string        `json:"username"`
		AvatarURL string        `json:"avatar_url"`
		TTS       bool          `json:"tts"`
		Embeds    []EmbedObject `json:"embeds"`
	}

	// Plugin values.
	Plugin struct {
		Repo    Repo
		Build   Build
		Config  Config
		Payload Payload
	}
)

// Exec executes the plugin.
func (p *Plugin) Exec() error {
	if len(p.Config.WebhookID) == 0 || len(p.Config.WebhookToken) == 0 {
		log.Println("missing discord config")

		return errors.New("missing discord config")
	}

	if p.Config.Drone {
		p.DroneTemplate()
		err := p.Send()
		if err != nil {
			return err
		}
	}

	if len(p.Config.Message) > 0 {
		for _, m := range p.Config.Message {
			txt, err := template.RenderTrim(m, p)
			if err != nil {
				return err
			}

			// update content
			p.Payload.Content = txt
			err = p.Send()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// Send discord message.
func (p *Plugin) Send() error {
	webhookURL := fmt.Sprintf("https://discordapp.com/api/webhooks/%s/%s", p.Config.WebhookID, p.Config.WebhookToken)
	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(p.Payload)
	_, err := http.Post(webhookURL, "application/json; charset=utf-8", b)

	if err != nil {
		return err
	}

	return nil
}

// DroneTemplate is plugin default template for Drone CI.
func (p *Plugin) DroneTemplate() {
	description := ""
	switch p.Build.Event {
	case "push":
		description = fmt.Sprintf("%s pushed to %s", p.Build.Author, p.Build.Branch)
	case "pull_request":
		description = fmt.Sprintf("%s created pull request %s", p.Build.Author, p.Build.Branch)
	case "tag":
		description = fmt.Sprintf("%s pushed tag %s", p.Build.Author, p.Build.Branch)
	}

	p.Payload.Embeds = []EmbedObject{
		{
			Title:       p.Build.Message,
			Description: description,
			URL:         p.Build.Link,
			Color:       p.Color(),
			Author: EmbedAuthorObject{
				Name:    p.Build.Author,
				IconURL: p.Build.Avatar,
			},
			Footer: EmbedFooterObject{
				Text:    "Powered by Drone Discord Plugin",
				IconURL: "https://c1.staticflickr.com/5/4236/34957940160_435d83114f_z.jpg",
			},
		},
	}
}

// Color code of the embed
func (p *Plugin) Color() int {
	if p.Config.Color != "" {
		p.Config.Color = strings.Replace(p.Config.Color, "#", "", -1)
		if s, err := strconv.ParseInt(p.Config.Color, 16, 32); err == nil {
			return int(s)
		}
	}

	switch p.Build.Status {
	case "success":
		// #1ac600 green
		return 1754624
	case "failure", "error", "killed":
		// #ff3232 red
		return 16724530
	default:
		// #ffd930 yellow
		return 16767280
	}
}
<commit_msg>update<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/appleboy/drone-facebook/template"
)

type (
	// Repo information
	Repo struct {
		Owner string
		Name  string
	}

	// Build information
	Build struct {
		Tag      string
		Event    string
		Number   int
		Commit   string
		Branch   string
		Author   string
		Avatar   string
		Message  string
		Email    string
		Status   string
		Link     string
		Started  float64
		Finished float64
	}

	// Config for the plugin.
	Config struct {
		WebhookID    string
		WebhookToken string
		Color        string
		Message      []string
		Drone        bool
	}

	// EmbedFooterObject for Embed Footer Structure.
	EmbedFooterObject struct {
		Text    string `json:"text"`
		IconURL string `json:"icon_url"`
	}

	// EmbedAuthorObject for Embed Author Structure
	EmbedAuthorObject struct {
		Name    string `json:"name"`
		URL     string `json:"url"`
		IconURL string `json:"icon_url"`
	}

	// EmbedFieldObject for Embed Field Structure
	EmbedFieldObject struct {
		Name  string `json:"name"`
		Value string `json:"value"`
	}

	// EmbedObject is for Embed Structure
	EmbedObject struct {
		Title       string             `json:"title"`
		Description string             `json:"description"`
		URL         string             `json:"url"`
		Color       int                `json:"color"`
		Footer      EmbedFooterObject  `json:"footer"`
		Author      EmbedAuthorObject  `json:"author"`
		Fields      []EmbedFieldObject `json:"fields"`
	}

	// Payload struct
	Payload struct {
		Wait      bool          `json:"wait"`
		Content   string        `json:"content"`
		Username  string        `json:"username"`
		AvatarURL string        `json:"avatar_url"`
		TTS       bool          `json:"tts"`
		Embeds    []EmbedObject `json:"embeds"`
	}

	// Plugin values.
	Plugin struct {
		Repo    Repo
		Build   Build
		Config  Config
		Payload Payload
	}
)

// Exec executes the plugin.
func (p *Plugin) Exec() error {
	if len(p.Config.WebhookID) == 0 || len(p.Config.WebhookToken) == 0 {
		log.Println("missing discord config")

		return errors.New("missing discord config")
	}

	if p.Config.Drone {
		object := p.DroneTemplate()
		p.Payload.Embeds = []EmbedObject{object}
		err := p.Send()
		if err != nil {
			return err
		}
	}

	if len(p.Config.Message) > 0 {
		for _, m := range p.Config.Message {
			txt, err := template.RenderTrim(m, p)
			if err != nil {
				return err
			}

			// update content
			p.Payload.Content = txt
			err = p.Send()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// Send discord message.
func (p *Plugin) Send() error {
	webhookURL := fmt.Sprintf("https://discordapp.com/api/webhooks/%s/%s", p.Config.WebhookID, p.Config.WebhookToken)
	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(p.Payload)
	_, err := http.Post(webhookURL, "application/json; charset=utf-8", b)

	if err != nil {
		return err
	}

	return nil
}

// DroneTemplate is plugin default template for Drone CI.
func (p *Plugin) DroneTemplate() EmbedObject {
	description := ""
	switch p.Build.Event {
	case "push":
		description = fmt.Sprintf("%s pushed to %s", p.Build.Author, p.Build.Branch)
	case "pull_request":
		description = fmt.Sprintf("%s created pull request %s", p.Build.Author, p.Build.Branch)
	case "tag":
		description = fmt.Sprintf("%s pushed tag %s", p.Build.Author, p.Build.Branch)
	}

	return EmbedObject{
		Title:       p.Build.Message,
		Description: description,
		URL:         p.Build.Link,
		Color:       p.Color(),
		Author: EmbedAuthorObject{
			Name:    p.Build.Author,
			IconURL: p.Build.Avatar,
		},
		Footer: EmbedFooterObject{
			Text:    "Powered by Drone Discord Plugin",
			IconURL: "https://c1.staticflickr.com/5/4236/34957940160_435d83114f_z.jpg",
		},
	}
}

// Color code of the embed
func (p *Plugin) Color() int {
	if p.Config.Color != "" {
		p.Config.Color = strings.Replace(p.Config.Color, "#", "", -1)
		if s, err := strconv.ParseInt(p.Config.Color, 16, 32); err == nil {
			return int(s)
		}
	}

	switch p.Build.Status {
	case "success":
		// #1ac600 green
		return 1754624
	case "failure", "error", "killed":
		// #ff3232 red
		return 16724530
	default:
		// #ffd930 yellow
		return 16767280
	}
}
<|endoftext|>


<commit_before><commit_msg>Extract pager renderer into separate function<commit_after><|endoftext|>


<commit_before>// Package types is where exportable API structures go. This is so we can share
// the XML marshalling and unmarshalling with the services.
package types

import (
	"encoding/xml"
)

type Version struct {
	XMLName xml.Name `xml:"version"`
	App     *App     `xml:"app"`
	Package *Package `xml:"package"`
}

type App struct {
	XMLName xml.Name `xml:"app"`
	Id      string   `xml:"id,attr"`
	Version string   `xml:"version,attr"`
	Track   string   `xml:"track,attr"`
}

type Package struct {
	XMLName   xml.Name `xml:"package"`
	Name      string   `xml:"name,attr"`      // Package filename
	Size      string   `xml:"size,attr"`      // Size of the file (in bytes)
	Path      string   `xml:"path,attr"`      // Path from the root to the file
	Sha1Sum   string   `xml:"sha1sum,attr"`   // SHA-1 hash of the file
	Sha256Sum string   `xml:"sha256sum,attr"` // Sha-256 hash of the file (extension)
	Required  bool     `xml:"required,attr"`
}
<commit_msg>fix(update/types): go fmt<commit_after>// Package types is where exportable API structures go. This is so we can share
// the XML marshalling and unmarshalling with the services.
package types

import (
	"encoding/xml"
)

type Version struct {
	XMLName xml.Name `xml:"version"`
	App     *App     `xml:"app"`
	Package *Package `xml:"package"`
}

type App struct {
	XMLName xml.Name `xml:"app"`
	Id      string   `xml:"id,attr"`
	Version string   `xml:"version,attr"`
	Track   string   `xml:"track,attr"`
}

type Package struct {
	XMLName              xml.Name `xml:"package"`
	Name                 string   `xml:"name,attr"`      // Package filename
	Size                 string   `xml:"size,attr"`      // Size of the file (in bytes)
	Path                 string   `xml:"path,attr"`      // Path from the root to the file
	Sha1Sum              string   `xml:"sha1sum,attr"`   // SHA-1 hash of the file
	Sha256Sum            string   `xml:"sha256sum,attr"` // Sha-256 hash of the file (extension)
	Required             bool     `xml:"required,attr"`
}
<|endoftext|>


<commit_before>package aws

import (
	"testing"

	"github.com/aws/aws-sdk-go/service/backup"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccAwsBackupRegionSettings_basic(t *testing.T) {
	var settings backup.DescribeRegionSettingsOutput

	rName := acctest.RandomWithPrefix("tf-acc-test")
	resourceName := "aws_backup_region_settings.test"
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() {
			testAccPreCheck(t)
			testAccPartitionHasServicePreCheck(fsx.EndpointsID, t)
			testAccPreCheckAWSBackup(t)
		},
		Providers:    testAccProviders,
		CheckDestroy: nil,
		Steps: []resource.TestStep{
			{
				Config: testAccBackupRegionSettingsConfig1(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsBackupRegionSettingsExists(&settings),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "8"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.DynamoDB", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Aurora", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EBS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EC2", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EFS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.FSx", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.RDS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Storage Gateway", "true"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccBackupRegionSettingsConfig2(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsBackupRegionSettingsExists(&settings),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "8"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.DynamoDB", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Aurora", "false"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EBS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EC2", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EFS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.FSx", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.RDS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Storage Gateway", "true"),
				),
			},
			{
				Config: testAccBackupRegionSettingsConfig1(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsBackupRegionSettingsExists(&settings),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "8"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.DynamoDB", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Aurora", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EBS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EC2", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EFS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.FSx", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.RDS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Storage Gateway", "true"),
				),
			},
		},
	})
}

func testAccCheckAwsBackupRegionSettingsExists(settings *backup.DescribeRegionSettingsOutput) resource.TestCheckFunc {
	return func(s *terraform.State) error {

		conn := testAccProvider.Meta().(*AWSClient).backupconn
		resp, err := conn.DescribeRegionSettings(&backup.DescribeRegionSettingsInput{})
		if err != nil {
			return err
		}

		*settings = *resp

		return nil
	}
}

func testAccBackupRegionSettingsConfig1(rName string) string {
	return `
resource "aws_backup_region_settings" "test" {
  resource_type_opt_in_preference = {
    "DynamoDB"        = true
    "Aurora"          = true
    "EBS"             = true
    "EC2"             = true
    "EFS"             = true
    "FSx"             = true
    "RDS"             = true
    "Storage Gateway" = true
  }
}
`
}

func testAccBackupRegionSettingsConfig2(rName string) string {
	return `
resource "aws_backup_region_settings" "test" {
  resource_type_opt_in_preference = {
    "DynamoDB"        = true
    "Aurora"          = false
    "EBS"             = true
    "EC2"             = true
    "EFS"             = true
    "FSx"             = true
    "RDS"             = true
    "Storage Gateway" = true
  }
}
`
}
<commit_msg>Update aws/resource_aws_backup_region_settings_test.go<commit_after>package aws

import (
	"testing"

	"github.com/aws/aws-sdk-go/service/backup"
	"github.com/aws/aws-sdk-go/service/fsx"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccAwsBackupRegionSettings_basic(t *testing.T) {
	var settings backup.DescribeRegionSettingsOutput

	rName := acctest.RandomWithPrefix("tf-acc-test")
	resourceName := "aws_backup_region_settings.test"
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() {
			testAccPreCheck(t)
			testAccPartitionHasServicePreCheck(fsx.EndpointsID, t)
			testAccPreCheckAWSBackup(t)
		},
		Providers:    testAccProviders,
		CheckDestroy: nil,
		Steps: []resource.TestStep{
			{
				Config: testAccBackupRegionSettingsConfig1(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsBackupRegionSettingsExists(&settings),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "8"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.DynamoDB", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Aurora", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EBS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EC2", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EFS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.FSx", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.RDS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Storage Gateway", "true"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccBackupRegionSettingsConfig2(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsBackupRegionSettingsExists(&settings),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "8"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.DynamoDB", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Aurora", "false"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EBS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EC2", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EFS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.FSx", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.RDS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Storage Gateway", "true"),
				),
			},
			{
				Config: testAccBackupRegionSettingsConfig1(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsBackupRegionSettingsExists(&settings),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.%", "8"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.DynamoDB", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Aurora", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EBS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EC2", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.EFS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.FSx", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.RDS", "true"),
					resource.TestCheckResourceAttr(resourceName, "resource_type_opt_in_preference.Storage Gateway", "true"),
				),
			},
		},
	})
}

func testAccCheckAwsBackupRegionSettingsExists(settings *backup.DescribeRegionSettingsOutput) resource.TestCheckFunc {
	return func(s *terraform.State) error {

		conn := testAccProvider.Meta().(*AWSClient).backupconn
		resp, err := conn.DescribeRegionSettings(&backup.DescribeRegionSettingsInput{})
		if err != nil {
			return err
		}

		*settings = *resp

		return nil
	}
}

func testAccBackupRegionSettingsConfig1(rName string) string {
	return `
resource "aws_backup_region_settings" "test" {
  resource_type_opt_in_preference = {
    "DynamoDB"        = true
    "Aurora"          = true
    "EBS"             = true
    "EC2"             = true
    "EFS"             = true
    "FSx"             = true
    "RDS"             = true
    "Storage Gateway" = true
  }
}
`
}

func testAccBackupRegionSettingsConfig2(rName string) string {
	return `
resource "aws_backup_region_settings" "test" {
  resource_type_opt_in_preference = {
    "DynamoDB"        = true
    "Aurora"          = false
    "EBS"             = true
    "EC2"             = true
    "EFS"             = true
    "FSx"             = true
    "RDS"             = true
    "Storage Gateway" = true
  }
}
`
}
<|endoftext|>


<commit_before>//this file contains several examples by Golang
package main

import (
	"fmt"
)

func main() {

	//Check if number is odd or even
	fmt.Print("Enter a number: ")
	var number int
	fmt.Scanf("%d", &number)

	if (number % 2 == 0) {
		fmt.Printf("%d is even number\n", number)
	} else {
		fmt.Printf("%d is odd number\n", number)
	}

}<commit_msg>Refactor code, move the code in main function to the other function<commit_after>//this file contains several examples by Golang
package main

import (
	"fmt"
)

func main() {

	checkNumberIsEvenOrOdd()

}

func checkNumberIsEvenOrOdd() {

	fmt.Print("Enter a number: ")
	var number int
	fmt.Scanf("%d", &number)

	if (number % 2 == 0) {
		fmt.Printf("%d is even number\n", number)
	} else {
		fmt.Printf("%d is odd number\n", number)
	}

}
<|endoftext|>


<commit_before>package backends
<commit_msg>auth backend interface<commit_after>package backends

import (
	"bytes"
	"fmt"
	"github.com/boltdb/bolt"
)

type AuthBackend interface {
	SetValue(key, value []byte) error
	GetValue(key []byte) ([]byte, error)
	Delete(key []byte) error
}
<|endoftext|>


<commit_before><commit_msg>Refactor parser code, modularize functions, implement functionality<commit_after><|endoftext|>


<commit_before>/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package framework

import (
	"fmt"
	"strings"
	"time"

	. "github.com/onsi/gomega"

	api "k8s.io/api/core/v1"
	core "k8s.io/api/core/v1"
	extensions "k8s.io/api/extensions/v1beta1"
	k8sErrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/kubernetes"
	podutil "k8s.io/kubernetes/pkg/api/v1/pod"
)

// EnsureSecret creates a Secret object or returns it if it already exists.
func (f *Framework) EnsureSecret(secret *api.Secret) *api.Secret {
	s, err := f.KubeClientSet.CoreV1().Secrets(secret.Namespace).Create(secret)
	if err != nil {
		if k8sErrors.IsAlreadyExists(err) {
			s, err := f.KubeClientSet.CoreV1().Secrets(secret.Namespace).Update(secret)
			Expect(err).NotTo(HaveOccurred(), "unexpected error updating secret")

			return s
		}

		Expect(err).NotTo(HaveOccurred(), "unexpected error creating secret")
	}

	Expect(s).NotTo(BeNil())
	Expect(s.ObjectMeta).NotTo(BeNil())

	return s
}

// EnsureConfigMap creates a ConfigMap object or returns it if it already exists.
func (f *Framework) EnsureConfigMap(configMap *api.ConfigMap) (*api.ConfigMap, error) {
	cm, err := f.KubeClientSet.CoreV1().ConfigMaps(configMap.Namespace).Create(configMap)
	if err != nil {
		if k8sErrors.IsAlreadyExists(err) {
			return f.KubeClientSet.CoreV1().ConfigMaps(configMap.Namespace).Update(configMap)
		}
		return nil, err
	}

	return cm, nil
}

// EnsureIngress creates an Ingress object or returns it if it already exists.
func (f *Framework) EnsureIngress(ingress *extensions.Ingress) *extensions.Ingress {
	ing, err := f.KubeClientSet.ExtensionsV1beta1().Ingresses(ingress.Namespace).Update(ingress)
	if err != nil {
		if k8sErrors.IsNotFound(err) {
			ing, err = f.KubeClientSet.ExtensionsV1beta1().Ingresses(ingress.Namespace).Create(ingress)
			Expect(err).NotTo(HaveOccurred(), "unexpected error creating ingress")
			return ing
		}

		Expect(err).NotTo(HaveOccurred())
	}

	Expect(ing).NotTo(BeNil())

	if ing.Annotations == nil {
		ing.Annotations = make(map[string]string)
	}

	return ing
}

// EnsureService creates a Service object or returns it if it already exists.
func (f *Framework) EnsureService(service *core.Service) *core.Service {
	s, err := f.KubeClientSet.CoreV1().Services(service.Namespace).Update(service)
	if err != nil {
		if k8sErrors.IsNotFound(err) {
			s, err := f.KubeClientSet.CoreV1().Services(service.Namespace).Create(service)
			Expect(err).NotTo(HaveOccurred(), "unexpected error creating service")
			return s

		}

		Expect(err).NotTo(HaveOccurred())
	}

	Expect(s).NotTo(BeNil(), "expected a service but none returned")

	return s
}

// EnsureDeployment creates a Deployment object or returns it if it already exists.
func (f *Framework) EnsureDeployment(deployment *extensions.Deployment) (*extensions.Deployment, error) {
	d, err := f.KubeClientSet.Extensions().Deployments(deployment.Namespace).Update(deployment)
	if err != nil {
		if k8sErrors.IsNotFound(err) {
			return f.KubeClientSet.Extensions().Deployments(deployment.Namespace).Create(deployment)
		}
		return nil, err
	}
	return d, nil
}

// WaitForPodsReady waits for a given amount of time until a group of Pods is running in the given namespace.
func WaitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, expectedReplicas int, namespace string, opts metav1.ListOptions) error {
	return wait.Poll(2*time.Second, timeout, func() (bool, error) {
		pl, err := kubeClientSet.CoreV1().Pods(namespace).List(opts)
		if err != nil {
			return false, err
		}

		r := 0
		for _, p := range pl.Items {
			if isRunning, _ := podRunningReady(&p); isRunning {
				r++
			}
		}

		if r == expectedReplicas {
			return true, nil
		}

		return false, nil
	})
}

// WaitForEndpoints waits for a given amount of time until an endpoint contains.
func WaitForEndpoints(kubeClientSet kubernetes.Interface, timeout time.Duration, name, ns string, expectedEndpoints int) error {
	return wait.Poll(2*time.Second, timeout, func() (bool, error) {
		endpoint, err := kubeClientSet.CoreV1().Endpoints(ns).Get(name, metav1.GetOptions{})
		if k8sErrors.IsNotFound(err) {
			return false, err
		}
		Expect(err).NotTo(HaveOccurred())
		if len(endpoint.Subsets) == 0 || len(endpoint.Subsets[0].Addresses) == 0 {
			return false, err
		}

		r := 0
		for _, es := range endpoint.Subsets {
			r += len(es.Addresses)
		}

		if r == expectedEndpoints {
			return true, nil
		}

		return false, nil
	})
}

// podRunningReady checks whether pod p's phase is running and it has a ready
// condition of status true.
func podRunningReady(p *core.Pod) (bool, error) {
	// Check the phase is running.
	if p.Status.Phase != core.PodRunning {
		return false, fmt.Errorf("want pod '%s' on '%s' to be '%v' but was '%v'",
			p.ObjectMeta.Name, p.Spec.NodeName, core.PodRunning, p.Status.Phase)
	}
	// Check the ready condition is true.
	if !podutil.IsPodReady(p) {
		return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v",
			p.ObjectMeta.Name, p.Spec.NodeName, core.PodReady, core.ConditionTrue, p.Status.Conditions)
	}
	return true, nil
}

func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Pod, error) {
	l, err := kubeClientSet.CoreV1().Pods(ns).List(metav1.ListOptions{
		LabelSelector: "app.kubernetes.io/name=ingress-nginx",
	})
	if err != nil {
		return nil, err
	}

	if len(l.Items) == 0 {
		return nil, fmt.Errorf("There is no ingress-nginx pods running in namespace %v", ns)
	}

	var pod *core.Pod

	for _, p := range l.Items {
		if strings.HasPrefix(p.GetName(), "nginx-ingress-controller") {
			if isRunning, err := podRunningReady(&p); err == nil && isRunning {
				pod = &p
				break
			}
		}
	}

	if pod == nil {
		return nil, fmt.Errorf("There is no ingress-nginx pods running in namespace %v", ns)
	}

	return pod, nil
}
<commit_msg>do not wait for endpoints that shouldn't exist<commit_after>/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package framework

import (
	"fmt"
	"strings"
	"time"

	. "github.com/onsi/gomega"

	api "k8s.io/api/core/v1"
	core "k8s.io/api/core/v1"
	extensions "k8s.io/api/extensions/v1beta1"
	k8sErrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/kubernetes"
	podutil "k8s.io/kubernetes/pkg/api/v1/pod"
)

// EnsureSecret creates a Secret object or returns it if it already exists.
func (f *Framework) EnsureSecret(secret *api.Secret) *api.Secret {
	s, err := f.KubeClientSet.CoreV1().Secrets(secret.Namespace).Create(secret)
	if err != nil {
		if k8sErrors.IsAlreadyExists(err) {
			s, err := f.KubeClientSet.CoreV1().Secrets(secret.Namespace).Update(secret)
			Expect(err).NotTo(HaveOccurred(), "unexpected error updating secret")

			return s
		}

		Expect(err).NotTo(HaveOccurred(), "unexpected error creating secret")
	}

	Expect(s).NotTo(BeNil())
	Expect(s.ObjectMeta).NotTo(BeNil())

	return s
}

// EnsureConfigMap creates a ConfigMap object or returns it if it already exists.
func (f *Framework) EnsureConfigMap(configMap *api.ConfigMap) (*api.ConfigMap, error) {
	cm, err := f.KubeClientSet.CoreV1().ConfigMaps(configMap.Namespace).Create(configMap)
	if err != nil {
		if k8sErrors.IsAlreadyExists(err) {
			return f.KubeClientSet.CoreV1().ConfigMaps(configMap.Namespace).Update(configMap)
		}
		return nil, err
	}

	return cm, nil
}

// EnsureIngress creates an Ingress object or returns it if it already exists.
func (f *Framework) EnsureIngress(ingress *extensions.Ingress) *extensions.Ingress {
	ing, err := f.KubeClientSet.ExtensionsV1beta1().Ingresses(ingress.Namespace).Update(ingress)
	if err != nil {
		if k8sErrors.IsNotFound(err) {
			ing, err = f.KubeClientSet.ExtensionsV1beta1().Ingresses(ingress.Namespace).Create(ingress)
			Expect(err).NotTo(HaveOccurred(), "unexpected error creating ingress")
			return ing
		}

		Expect(err).NotTo(HaveOccurred())
	}

	Expect(ing).NotTo(BeNil())

	if ing.Annotations == nil {
		ing.Annotations = make(map[string]string)
	}

	return ing
}

// EnsureService creates a Service object or returns it if it already exists.
func (f *Framework) EnsureService(service *core.Service) *core.Service {
	s, err := f.KubeClientSet.CoreV1().Services(service.Namespace).Update(service)
	if err != nil {
		if k8sErrors.IsNotFound(err) {
			s, err := f.KubeClientSet.CoreV1().Services(service.Namespace).Create(service)
			Expect(err).NotTo(HaveOccurred(), "unexpected error creating service")
			return s

		}

		Expect(err).NotTo(HaveOccurred())
	}

	Expect(s).NotTo(BeNil(), "expected a service but none returned")

	return s
}

// EnsureDeployment creates a Deployment object or returns it if it already exists.
func (f *Framework) EnsureDeployment(deployment *extensions.Deployment) (*extensions.Deployment, error) {
	d, err := f.KubeClientSet.Extensions().Deployments(deployment.Namespace).Update(deployment)
	if err != nil {
		if k8sErrors.IsNotFound(err) {
			return f.KubeClientSet.Extensions().Deployments(deployment.Namespace).Create(deployment)
		}
		return nil, err
	}
	return d, nil
}

// WaitForPodsReady waits for a given amount of time until a group of Pods is running in the given namespace.
func WaitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, expectedReplicas int, namespace string, opts metav1.ListOptions) error {
	return wait.Poll(2*time.Second, timeout, func() (bool, error) {
		pl, err := kubeClientSet.CoreV1().Pods(namespace).List(opts)
		if err != nil {
			return false, err
		}

		r := 0
		for _, p := range pl.Items {
			if isRunning, _ := podRunningReady(&p); isRunning {
				r++
			}
		}

		if r == expectedReplicas {
			return true, nil
		}

		return false, nil
	})
}

// WaitForEndpoints waits for a given amount of time until an endpoint contains.
func WaitForEndpoints(kubeClientSet kubernetes.Interface, timeout time.Duration, name, ns string, expectedEndpoints int) error {
	if expectedEndpoints == 0 {
		return nil
	}
	return wait.Poll(2*time.Second, timeout, func() (bool, error) {
		endpoint, err := kubeClientSet.CoreV1().Endpoints(ns).Get(name, metav1.GetOptions{})
		if k8sErrors.IsNotFound(err) {
			return false, err
		}
		Expect(err).NotTo(HaveOccurred())
		if len(endpoint.Subsets) == 0 || len(endpoint.Subsets[0].Addresses) == 0 {
			return false, err
		}

		r := 0
		for _, es := range endpoint.Subsets {
			r += len(es.Addresses)
		}

		if r == expectedEndpoints {
			return true, nil
		}

		return false, nil
	})
}

// podRunningReady checks whether pod p's phase is running and it has a ready
// condition of status true.
func podRunningReady(p *core.Pod) (bool, error) {
	// Check the phase is running.
	if p.Status.Phase != core.PodRunning {
		return false, fmt.Errorf("want pod '%s' on '%s' to be '%v' but was '%v'",
			p.ObjectMeta.Name, p.Spec.NodeName, core.PodRunning, p.Status.Phase)
	}
	// Check the ready condition is true.
	if !podutil.IsPodReady(p) {
		return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v",
			p.ObjectMeta.Name, p.Spec.NodeName, core.PodReady, core.ConditionTrue, p.Status.Conditions)
	}
	return true, nil
}

func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Pod, error) {
	l, err := kubeClientSet.CoreV1().Pods(ns).List(metav1.ListOptions{
		LabelSelector: "app.kubernetes.io/name=ingress-nginx",
	})
	if err != nil {
		return nil, err
	}

	if len(l.Items) == 0 {
		return nil, fmt.Errorf("There is no ingress-nginx pods running in namespace %v", ns)
	}

	var pod *core.Pod

	for _, p := range l.Items {
		if strings.HasPrefix(p.GetName(), "nginx-ingress-controller") {
			if isRunning, err := podRunningReady(&p); err == nil && isRunning {
				pod = &p
				break
			}
		}
	}

	if pod == nil {
		return nil, fmt.Errorf("There is no ingress-nginx pods running in namespace %v", ns)
	}

	return pod, nil
}
<|endoftext|>


<commit_before>package scheduler

import (
	"bytes"
	"net/http"
	"sync"
	"time"

	"github.com/op/go-logging"
	"github.com/satori/go.uuid"
	"golang.org/x/build/kubernetes"
	api "golang.org/x/build/kubernetes/api"
	"golang.org/x/net/context"
)

var log = logging.MustGetLogger("scheduler")

const KUBERNETES_BASE = "http://127.0.0.1:9000"
const DI_LABEL = "di-tag"

type kubectl struct {
	kubeClient *kubernetes.Client
}

func NewKubectl() (scheduler, error) {
	body := `{"apiVersion":"v1","kind":"Namespace",` +
		`"metadata":{"name":"kube-system"}}`
	url := "http://127.0.0.1:9000/api/v1/namespaces"
	ctype := "application/json"
	_, err := http.Post(url, ctype, bytes.NewBuffer([]byte(body)))
	if err != nil {
		return nil, err
	}

	kubeClient, err := kubernetes.NewClient(KUBERNETES_BASE, &http.Client{})
	if err != nil {
	}

	return kubectl{kubeClient: kubeClient}, nil
}

func (k kubectl) get() ([]Container, error) {
	pods, err := k.kubeClient.GetPods(ctx())
	if err != nil {
		return nil, err
	}

	var result []Container
	for _, pod := range pods {
		result = append(result, Container{
			ID:    pod.ObjectMeta.Name,
			IP:    pod.Status.PodIP,
			Label: pod.ObjectMeta.Labels[DI_LABEL],
		})
	}
	return result, err
}

func (k kubectl) boot(n int) {
	var wg sync.WaitGroup
	wg.Add(n)
	defer wg.Wait()

	for i := 0; i < n; i++ {
		go func() {
			k.bootContainer()
			wg.Done()
		}()
	}
}

func (k kubectl) terminate(ids []string) {
	for _, id := range ids {
		err := k.kubeClient.DeletePod(ctx(), id)
		if err != nil {
			log.Warning("Failed to delete pod %s: %s", id, err)
		} else {
			log.Info("Deleted pod: %s", id)
		}
	}
}

func (k kubectl) bootContainer() {
	id := uuid.NewV4().String()

	/* Since a pod is the atomic unit of kubernetes, we have to do this
	 * weird transform that maps containers to pods. E.g., if we say, "spawn
	 * 10 red containers", then this will be reflected as 10 separate pods
	 * in kubernetes. We do this primarily to allow more fine-grained
	 * control of things through the policy language. */
	_, err := k.kubeClient.RunPod(ctx(), &api.Pod{
		TypeMeta: api.TypeMeta{APIVersion: "v1", Kind: "Pod"},
		ObjectMeta: api.ObjectMeta{
			Name: id,
			Labels: map[string]string{
				DI_LABEL: id,
			},
		},
		Spec: api.PodSpec{
			Containers: []api.Container{{
				Name:    id,
				Image:   "ubuntu:14.04",
				Command: []string{"tail", "-f", "/dev/null"},
				TTY:     true},
			},
		},
	})

	if err != nil {
		log.Warning("Failed to start pod %s: %s", id, err)
	} else {
		log.Info("Booted pod: %s", id)
	}
}

func ctx() context.Context {
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	return ctx
}
<commit_msg>kubectl: Fixed miss error return<commit_after>package scheduler

import (
	"bytes"
	"net/http"
	"sync"
	"time"

	"github.com/op/go-logging"
	"github.com/satori/go.uuid"
	"golang.org/x/build/kubernetes"
	api "golang.org/x/build/kubernetes/api"
	"golang.org/x/net/context"
)

var log = logging.MustGetLogger("scheduler")

const KUBERNETES_BASE = "http://127.0.0.1:9000"
const DI_LABEL = "di-tag"

type kubectl struct {
	kubeClient *kubernetes.Client
}

func NewKubectl() (scheduler, error) {
	body := `{"apiVersion":"v1","kind":"Namespace",` +
		`"metadata":{"name":"kube-system"}}`
	url := "http://127.0.0.1:9000/api/v1/namespaces"
	ctype := "application/json"
	_, err := http.Post(url, ctype, bytes.NewBuffer([]byte(body)))
	if err != nil {
		return nil, err
	}

	kubeClient, err := kubernetes.NewClient(KUBERNETES_BASE, &http.Client{})
	if err != nil {
		return nil, err
	}

	return kubectl{kubeClient: kubeClient}, nil
}

func (k kubectl) get() ([]Container, error) {
	pods, err := k.kubeClient.GetPods(ctx())
	if err != nil {
		return nil, err
	}

	var result []Container
	for _, pod := range pods {
		result = append(result, Container{
			ID:    pod.ObjectMeta.Name,
			IP:    pod.Status.PodIP,
			Label: pod.ObjectMeta.Labels[DI_LABEL],
		})
	}
	return result, err
}

func (k kubectl) boot(n int) {
	var wg sync.WaitGroup
	wg.Add(n)
	defer wg.Wait()

	for i := 0; i < n; i++ {
		go func() {
			k.bootContainer()
			wg.Done()
		}()
	}
}

func (k kubectl) terminate(ids []string) {
	for _, id := range ids {
		err := k.kubeClient.DeletePod(ctx(), id)
		if err != nil {
			log.Warning("Failed to delete pod %s: %s", id, err)
		} else {
			log.Info("Deleted pod: %s", id)
		}
	}
}

func (k kubectl) bootContainer() {
	id := uuid.NewV4().String()

	/* Since a pod is the atomic unit of kubernetes, we have to do this
	 * weird transform that maps containers to pods. E.g., if we say, "spawn
	 * 10 red containers", then this will be reflected as 10 separate pods
	 * in kubernetes. We do this primarily to allow more fine-grained
	 * control of things through the policy language. */
	_, err := k.kubeClient.RunPod(ctx(), &api.Pod{
		TypeMeta: api.TypeMeta{APIVersion: "v1", Kind: "Pod"},
		ObjectMeta: api.ObjectMeta{
			Name: id,
			Labels: map[string]string{
				DI_LABEL: id,
			},
		},
		Spec: api.PodSpec{
			Containers: []api.Container{{
				Name:    id,
				Image:   "ubuntu:14.04",
				Command: []string{"tail", "-f", "/dev/null"},
				TTY:     true},
			},
		},
	})

	if err != nil {
		log.Warning("Failed to start pod %s: %s", id, err)
	} else {
		log.Info("Booted pod: %s", id)
	}
}

func ctx() context.Context {
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	return ctx
}
<|endoftext|>