<commit_before>package aws

import (
	"fmt"
	"regexp"
	"testing"

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

func TestAccAWSLambdaAlias_basic(t *testing.T) {
	var conf lambda.AliasConfiguration
	resourceName := "aws_lambda_alias.lambda_alias_test"

	rString := acctest.RandString(8)
	roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString)
	policyName := fmt.Sprintf("tf_acc_policy_lambda_alias_basic_%s", rString)
	attachmentName := fmt.Sprintf("tf_acc_attachment_%s", rString)
	funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString)
	aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsLambdaAliasDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
					resource.TestMatchResourceAttr(resourceName, "invoke_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:apigateway:[^:]+:lambda:path/2015-03-31/functions/arn:[^:]+:lambda:[^:]+:[^:]+:function:%s:%s/invocations$", funcName, aliasName))),
				),
			},
		},
	})
}

func TestAccAWSLambdaAlias_nameupdate(t *testing.T) {
	var conf lambda.AliasConfiguration
	resourceName := "aws_lambda_alias.lambda_alias_test"

	rString := acctest.RandString(8)
	roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString)
	policyName := fmt.Sprintf("tf_acc_policy_lambda_alias_basic_%s", rString)
	attachmentName := fmt.Sprintf("tf_acc_attachment_%s", rString)
	funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString)
	aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString)
	aliasNameUpdate := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", acctest.RandString(8))

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsLambdaAliasDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasNameUpdate),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasNameUpdate)),
				),
			},
		},
	})
}

func TestAccAWSLambdaAlias_routingconfig(t *testing.T) {
	var conf lambda.AliasConfiguration
	resourceName := "aws_lambda_alias.lambda_alias_test"

	rString := acctest.RandString(8)
	roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString)
	policyName := fmt.Sprintf("tf_acc_policy_lambda_alias_basic_%s", rString)
	attachmentName := fmt.Sprintf("tf_acc_attachment_%s", rString)
	funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString)
	aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsLambdaAliasDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
			{
				Config: testAccAwsLambdaAliasConfigWithRoutingConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckAwsLambdaAliasRoutingConfigExists(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
		},
	})
}

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

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

		_, err := conn.GetAlias(&lambda.GetAliasInput{
			FunctionName: aws.String(rs.Primary.ID),
		})

		if err == nil {
			return fmt.Errorf("Lambda alias was not deleted")
		}

	}

	return nil
}

func testAccCheckAwsLambdaAliasExists(n string, mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Lambda alias not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("Lambda alias not set")
		}

		conn := testAccProvider.Meta().(*AWSClient).lambdaconn

		params := &lambda.GetAliasInput{
			FunctionName: aws.String(rs.Primary.ID),
			Name:         aws.String(rs.Primary.Attributes["name"]),
		}

		getAliasConfiguration, err := conn.GetAlias(params)
		if err != nil {
			return err
		}

		*mapping = *getAliasConfiguration

		return nil
	}
}

func testAccCheckAwsLambdaAttributes(mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		name := *mapping.Name
		arn := *mapping.AliasArn
		if arn == "" {
			return fmt.Errorf("Could not read Lambda alias ARN")
		}
		if name == "" {
			return fmt.Errorf("Could not read Lambda alias name")
		}
		return nil
	}
}

func testAccCheckAwsLambdaAliasRoutingConfigExists(mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		routingConfig := mapping.RoutingConfig

		if routingConfig == nil {
			return fmt.Errorf("Could not read Lambda alias routing config")
		}
		if len(routingConfig.AdditionalVersionWeights) != 1 {
			return fmt.Errorf("Could not read Lambda alias additional version weights")
		}
		return nil
	}
}

func testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		routingConfig := mapping.RoutingConfig

		if routingConfig != nil {
			return fmt.Errorf("Lambda alias routing config still exists after removal")
		}
		return nil
	}
}

func testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName string) string {
	return fmt.Sprintf(`
resource "aws_iam_role" "iam_for_lambda" {
  name = "%s"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_policy" "policy_for_role" {
  name        = "%s"
  path        = "/"
  description = "IAM policy for for Lamda alias testing"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
            "lambda:*"
          ],
          "Resource": "*"
      }
  ]
}
EOF
}

resource "aws_iam_policy_attachment" "policy_attachment_for_role" {
  name       = "%s"
  roles      = ["${aws_iam_role.iam_for_lambda.name}"]
  policy_arn = "${aws_iam_policy.policy_for_role.arn}"
}

resource "aws_lambda_function" "lambda_function_test_create" {
  filename         = "test-fixtures/lambdatest.zip"
  function_name    = "%s"
  role             = "${aws_iam_role.iam_for_lambda.arn}"
  handler          = "exports.example"
  runtime          = "nodejs8.10"
  source_code_hash = "${base64sha256(file("test-fixtures/lambdatest.zip"))}"
  publish          = "true"
}

resource "aws_lambda_alias" "lambda_alias_test" {
  name             = "%s"
  description      = "a sample description"
  function_name    = "${aws_lambda_function.lambda_function_test_create.arn}"
  function_version = "1"
}`, roleName, policyName, attachmentName, funcName, aliasName)
}

func testAccAwsLambdaAliasConfigWithRoutingConfig(roleName, policyName, attachmentName, funcName, aliasName string) string {
	return fmt.Sprintf(`
resource "aws_iam_role" "iam_for_lambda" {
  name = "%s"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_policy" "policy_for_role" {
  name        = "%s"
  path        = "/"
  description = "IAM policy for for Lamda alias testing"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
            "lambda:*"
          ],
          "Resource": "*"
      }
  ]
}
EOF
}

resource "aws_iam_policy_attachment" "policy_attachment_for_role" {
  name       = "%s"
  roles      = ["${aws_iam_role.iam_for_lambda.name}"]
  policy_arn = "${aws_iam_policy.policy_for_role.arn}"
}

resource "aws_lambda_function" "lambda_function_test_create" {
  filename         = "test-fixtures/lambdatest_modified.zip"
  function_name    = "%s"
  role             = "${aws_iam_role.iam_for_lambda.arn}"
  handler          = "exports.example"
  runtime          = "nodejs8.10"
  source_code_hash = "${base64sha256(file("test-fixtures/lambdatest_modified.zip"))}"
  publish          = "true"
}

resource "aws_lambda_alias" "lambda_alias_test" {
  name             = "%s"
  description      = "a sample description"
  function_name    = "${aws_lambda_function.lambda_function_test_create.arn}"
  function_version = "1"
  routing_config   = {
    additional_version_weights = {
      "2" = 0.5
    }
  }
}`, roleName, policyName, attachmentName, funcName, aliasName)
}
<commit_msg>tests/resource/aws_lambda_alias: Use Terraform 0.11.12 and later compatible file hashing function<commit_after>package aws

import (
	"fmt"
	"regexp"
	"testing"

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

func TestAccAWSLambdaAlias_basic(t *testing.T) {
	var conf lambda.AliasConfiguration
	resourceName := "aws_lambda_alias.lambda_alias_test"

	rString := acctest.RandString(8)
	roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString)
	policyName := fmt.Sprintf("tf_acc_policy_lambda_alias_basic_%s", rString)
	attachmentName := fmt.Sprintf("tf_acc_attachment_%s", rString)
	funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString)
	aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsLambdaAliasDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
					resource.TestMatchResourceAttr(resourceName, "invoke_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:apigateway:[^:]+:lambda:path/2015-03-31/functions/arn:[^:]+:lambda:[^:]+:[^:]+:function:%s:%s/invocations$", funcName, aliasName))),
				),
			},
		},
	})
}

func TestAccAWSLambdaAlias_nameupdate(t *testing.T) {
	var conf lambda.AliasConfiguration
	resourceName := "aws_lambda_alias.lambda_alias_test"

	rString := acctest.RandString(8)
	roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString)
	policyName := fmt.Sprintf("tf_acc_policy_lambda_alias_basic_%s", rString)
	attachmentName := fmt.Sprintf("tf_acc_attachment_%s", rString)
	funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString)
	aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString)
	aliasNameUpdate := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", acctest.RandString(8))

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsLambdaAliasDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasNameUpdate),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasNameUpdate)),
				),
			},
		},
	})
}

func TestAccAWSLambdaAlias_routingconfig(t *testing.T) {
	var conf lambda.AliasConfiguration
	resourceName := "aws_lambda_alias.lambda_alias_test"

	rString := acctest.RandString(8)
	roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString)
	policyName := fmt.Sprintf("tf_acc_policy_lambda_alias_basic_%s", rString)
	attachmentName := fmt.Sprintf("tf_acc_attachment_%s", rString)
	funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString)
	aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsLambdaAliasDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
			{
				Config: testAccAwsLambdaAliasConfigWithRoutingConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckAwsLambdaAliasRoutingConfigExists(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
			{
				Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsLambdaAliasExists(resourceName, &conf),
					testAccCheckAwsLambdaAttributes(&conf),
					testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf),
					testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)),
				),
			},
		},
	})
}

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

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

		_, err := conn.GetAlias(&lambda.GetAliasInput{
			FunctionName: aws.String(rs.Primary.ID),
		})

		if err == nil {
			return fmt.Errorf("Lambda alias was not deleted")
		}

	}

	return nil
}

func testAccCheckAwsLambdaAliasExists(n string, mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Lambda alias not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("Lambda alias not set")
		}

		conn := testAccProvider.Meta().(*AWSClient).lambdaconn

		params := &lambda.GetAliasInput{
			FunctionName: aws.String(rs.Primary.ID),
			Name:         aws.String(rs.Primary.Attributes["name"]),
		}

		getAliasConfiguration, err := conn.GetAlias(params)
		if err != nil {
			return err
		}

		*mapping = *getAliasConfiguration

		return nil
	}
}

func testAccCheckAwsLambdaAttributes(mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		name := *mapping.Name
		arn := *mapping.AliasArn
		if arn == "" {
			return fmt.Errorf("Could not read Lambda alias ARN")
		}
		if name == "" {
			return fmt.Errorf("Could not read Lambda alias name")
		}
		return nil
	}
}

func testAccCheckAwsLambdaAliasRoutingConfigExists(mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		routingConfig := mapping.RoutingConfig

		if routingConfig == nil {
			return fmt.Errorf("Could not read Lambda alias routing config")
		}
		if len(routingConfig.AdditionalVersionWeights) != 1 {
			return fmt.Errorf("Could not read Lambda alias additional version weights")
		}
		return nil
	}
}

func testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(mapping *lambda.AliasConfiguration) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		routingConfig := mapping.RoutingConfig

		if routingConfig != nil {
			return fmt.Errorf("Lambda alias routing config still exists after removal")
		}
		return nil
	}
}

func testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName string) string {
	return fmt.Sprintf(`
resource "aws_iam_role" "iam_for_lambda" {
  name = "%s"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_policy" "policy_for_role" {
  name        = "%s"
  path        = "/"
  description = "IAM policy for for Lamda alias testing"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
            "lambda:*"
          ],
          "Resource": "*"
      }
  ]
}
EOF
}

resource "aws_iam_policy_attachment" "policy_attachment_for_role" {
  name       = "%s"
  roles      = ["${aws_iam_role.iam_for_lambda.name}"]
  policy_arn = "${aws_iam_policy.policy_for_role.arn}"
}

resource "aws_lambda_function" "lambda_function_test_create" {
  filename         = "test-fixtures/lambdatest.zip"
  function_name    = "%s"
  role             = "${aws_iam_role.iam_for_lambda.arn}"
  handler          = "exports.example"
  runtime          = "nodejs8.10"
  source_code_hash = "${filebase64sha256("test-fixtures/lambdatest.zip")}"
  publish          = "true"
}

resource "aws_lambda_alias" "lambda_alias_test" {
  name             = "%s"
  description      = "a sample description"
  function_name    = "${aws_lambda_function.lambda_function_test_create.arn}"
  function_version = "1"
}`, roleName, policyName, attachmentName, funcName, aliasName)
}

func testAccAwsLambdaAliasConfigWithRoutingConfig(roleName, policyName, attachmentName, funcName, aliasName string) string {
	return fmt.Sprintf(`
resource "aws_iam_role" "iam_for_lambda" {
  name = "%s"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_policy" "policy_for_role" {
  name        = "%s"
  path        = "/"
  description = "IAM policy for for Lamda alias testing"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
            "lambda:*"
          ],
          "Resource": "*"
      }
  ]
}
EOF
}

resource "aws_iam_policy_attachment" "policy_attachment_for_role" {
  name       = "%s"
  roles      = ["${aws_iam_role.iam_for_lambda.name}"]
  policy_arn = "${aws_iam_policy.policy_for_role.arn}"
}

resource "aws_lambda_function" "lambda_function_test_create" {
  filename         = "test-fixtures/lambdatest_modified.zip"
  function_name    = "%s"
  role             = "${aws_iam_role.iam_for_lambda.arn}"
  handler          = "exports.example"
  runtime          = "nodejs8.10"
  source_code_hash = "${filebase64sha256("test-fixtures/lambdatest_modified.zip")}"
  publish          = "true"
}

resource "aws_lambda_alias" "lambda_alias_test" {
  name             = "%s"
  description      = "a sample description"
  function_name    = "${aws_lambda_function.lambda_function_test_create.arn}"
  function_version = "1"

  routing_config {
    additional_version_weights = {
      "2" = 0.5
    }
  }
}`, roleName, policyName, attachmentName, funcName, aliasName)
}
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC All Rights Reserved.
//
// 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 daemon

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

	"github.com/google/go-containerregistry/pkg/name"
	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/tarball"
	"github.com/google/go-containerregistry/pkg/v1/types"
)

type image struct {
	ref          name.Reference
	opener       *imageOpener
	tarballImage v1.Image

	once sync.Once
	err  error
}

type imageOpener struct {
	ref name.Reference
	ctx context.Context

	buffered bool
	client   Client

	once  sync.Once
	bytes []byte
	err   error
}

func (i *imageOpener) saveImage() (io.ReadCloser, error) {
	return i.client.ImageSave(i.ctx, []string{i.ref.Name()})
}

func (i *imageOpener) bufferedOpener() (io.ReadCloser, error) {
	// Store the tarball in memory and return a new reader into the bytes each time we need to access something.
	i.once.Do(func() {
		i.bytes, i.err = func() ([]byte, error) {
			rc, err := i.saveImage()
			if err != nil {
				return nil, err
			}
			defer rc.Close()

			return ioutil.ReadAll(rc)
		}()
	})

	// Wrap the bytes in a ReadCloser so it looks like an opened file.
	return ioutil.NopCloser(bytes.NewReader(i.bytes)), i.err
}

func (i *imageOpener) opener() tarball.Opener {
	if i.buffered {
		return i.bufferedOpener
	}

	// To avoid storing the tarball in memory, do a save every time we need to access something.
	return i.saveImage
}

// Image provides access to an image reference from the Docker daemon,
// applying functional options to the underlying imageOpener before
// resolving the reference into a v1.Image.
func Image(ref name.Reference, options ...Option) (v1.Image, error) {
	o, err := makeOptions(options...)
	if err != nil {
		return nil, err
	}

	i := &imageOpener{
		ref:      ref,
		buffered: o.buffered,
		client:   o.client,
		ctx:      o.ctx,
	}

	return &image{
		ref:    ref,
		opener: i,
	}, nil
}

func (i *image) initialize() error {
	// Don't re-initialize tarball if already initialized.
	if i.tarballImage == nil {
		i.once.Do(func() {
			i.tarballImage, i.err = tarball.Image(i.opener.opener(), nil)
		})
	}
	return i.err
}

func (i *image) Layers() ([]v1.Layer, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.Layers()
}

func (i *image) MediaType() (types.MediaType, error) {
	if err := i.initialize(); err != nil {
		return "", err
	}
	return i.tarballImage.MediaType()
}

func (i *image) Size() (int64, error) {
	if err := i.initialize(); err != nil {
		return 0, err
	}
	return i.tarballImage.Size()
}

func (i *image) ConfigName() (v1.Hash, error) {
	res, _, err := i.opener.client.ImageInspectWithRaw(i.opener.ctx, i.ref.String())
	if err != nil {
		return v1.Hash{}, err
	}
	return v1.NewHash(res.ID)
}

func (i *image) ConfigFile() (*v1.ConfigFile, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.ConfigFile()
}

func (i *image) RawConfigFile() ([]byte, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.RawConfigFile()
}

func (i *image) Digest() (v1.Hash, error) {
	if err := i.initialize(); err != nil {
		return v1.Hash{}, err
	}
	return i.tarballImage.Digest()
}

func (i *image) Manifest() (*v1.Manifest, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.Manifest()
}

func (i *image) RawManifest() ([]byte, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.RawManifest()
}

func (i *image) LayerByDigest(h v1.Hash) (v1.Layer, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.LayerByDigest(h)
}

func (i *image) LayerByDiffID(h v1.Hash) (v1.Layer, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.LayerByDiffID(h)
}
<commit_msg>Eagerly fetch image ID in daemon.Image (#1272)<commit_after>// Copyright 2018 Google LLC All Rights Reserved.
//
// 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 daemon

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

	"github.com/google/go-containerregistry/pkg/name"
	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/tarball"
	"github.com/google/go-containerregistry/pkg/v1/types"
)

type image struct {
	ref          name.Reference
	opener       *imageOpener
	tarballImage v1.Image
	id           *v1.Hash

	once sync.Once
	err  error
}

type imageOpener struct {
	ref name.Reference
	ctx context.Context

	buffered bool
	client   Client

	once  sync.Once
	bytes []byte
	err   error
}

func (i *imageOpener) saveImage() (io.ReadCloser, error) {
	return i.client.ImageSave(i.ctx, []string{i.ref.Name()})
}

func (i *imageOpener) bufferedOpener() (io.ReadCloser, error) {
	// Store the tarball in memory and return a new reader into the bytes each time we need to access something.
	i.once.Do(func() {
		i.bytes, i.err = func() ([]byte, error) {
			rc, err := i.saveImage()
			if err != nil {
				return nil, err
			}
			defer rc.Close()

			return ioutil.ReadAll(rc)
		}()
	})

	// Wrap the bytes in a ReadCloser so it looks like an opened file.
	return ioutil.NopCloser(bytes.NewReader(i.bytes)), i.err
}

func (i *imageOpener) opener() tarball.Opener {
	if i.buffered {
		return i.bufferedOpener
	}

	// To avoid storing the tarball in memory, do a save every time we need to access something.
	return i.saveImage
}

// Image provides access to an image reference from the Docker daemon,
// applying functional options to the underlying imageOpener before
// resolving the reference into a v1.Image.
func Image(ref name.Reference, options ...Option) (v1.Image, error) {
	o, err := makeOptions(options...)
	if err != nil {
		return nil, err
	}

	i := &imageOpener{
		ref:      ref,
		buffered: o.buffered,
		client:   o.client,
		ctx:      o.ctx,
	}

	img := &image{
		ref:    ref,
		opener: i,
	}

	// Eagerly fetch Image ID to ensure it actually exists.
	// https://github.com/google/go-containerregistry/issues/1186
	id, err := img.ConfigName()
	if err != nil {
		return nil, err
	}
	img.id = &id

	return img, nil
}

func (i *image) initialize() error {
	// Don't re-initialize tarball if already initialized.
	if i.tarballImage == nil {
		i.once.Do(func() {
			i.tarballImage, i.err = tarball.Image(i.opener.opener(), nil)
		})
	}
	return i.err
}

func (i *image) Layers() ([]v1.Layer, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.Layers()
}

func (i *image) MediaType() (types.MediaType, error) {
	if err := i.initialize(); err != nil {
		return "", err
	}
	return i.tarballImage.MediaType()
}

func (i *image) Size() (int64, error) {
	if err := i.initialize(); err != nil {
		return 0, err
	}
	return i.tarballImage.Size()
}

func (i *image) ConfigName() (v1.Hash, error) {
	if i.id != nil {
		return *i.id, nil
	}
	res, _, err := i.opener.client.ImageInspectWithRaw(i.opener.ctx, i.ref.String())
	if err != nil {
		return v1.Hash{}, err
	}
	return v1.NewHash(res.ID)
}

func (i *image) ConfigFile() (*v1.ConfigFile, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.ConfigFile()
}

func (i *image) RawConfigFile() ([]byte, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.RawConfigFile()
}

func (i *image) Digest() (v1.Hash, error) {
	if err := i.initialize(); err != nil {
		return v1.Hash{}, err
	}
	return i.tarballImage.Digest()
}

func (i *image) Manifest() (*v1.Manifest, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.Manifest()
}

func (i *image) RawManifest() ([]byte, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.RawManifest()
}

func (i *image) LayerByDigest(h v1.Hash) (v1.Layer, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.LayerByDigest(h)
}

func (i *image) LayerByDiffID(h v1.Hash) (v1.Layer, error) {
	if err := i.initialize(); err != nil {
		return nil, err
	}
	return i.tarballImage.LayerByDiffID(h)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
)

const Version = "1.0.0"

func displayVersion(w io.Writer) {
	fmt.Fprintf(w, "ccat v%s\n", Version)
}
<commit_msg>Bump to 1.1.0<commit_after>package main

import (
	"fmt"
	"io"
)

const Version = "1.1.0"

func displayVersion(w io.Writer) {
	fmt.Fprintf(w, "ccat v%s\n", Version)
}
<|endoftext|>


<commit_before>// Copyright 2016 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

package pine64

import (
	"errors"
	"os"

	"periph.io/x/periph"
	"periph.io/x/periph/conn/pin"
	"periph.io/x/periph/conn/pin/pinreg"
	"periph.io/x/periph/host/allwinner"
)

// Present returns true if running on a Pine64 board.
//
// https://www.pine64.org/
func Present() bool {
	if isArm {
		// This is iffy at best.
		_, err := os.Stat("/boot/pine64.dtb")
		return err == nil
	}
	return false
}

// Pine64 specific pins.
var (
	VCC         = &pin.BasicPin{N: "VCC"}         //
	IOVCC       = &pin.BasicPin{N: "IOVCC"}       // Power supply for port A
	TEMP_SENSOR = &pin.BasicPin{N: "TEMP_SENSOR"} //
	IR_RX       = &pin.BasicPin{N: "IR_RX"}       // IR Data Receive
	CHARGER_LED = &pin.BasicPin{N: "CHARGER_LED"} //
	RESET       = &pin.BasicPin{N: "RESET"}       //
	PWR_SWITCH  = &pin.BasicPin{N: "PWR_SWITCH "} //
)

// All the individual pins on the headers.
var (
	P1_1  = pin.V3_3       // max 40mA
	P1_2  = pin.V5         // (filtered)
	P1_3  = allwinner.PH3  //
	P1_4  = pin.V5         // (filtered)
	P1_5  = allwinner.PH2  //
	P1_6  = pin.GROUND     //
	P1_7  = allwinner.PL10 //
	P1_8  = allwinner.PB0  //
	P1_9  = pin.GROUND     //
	P1_10 = allwinner.PB1  //
	P1_11 = allwinner.PC7  //
	P1_12 = allwinner.PC8  //
	P1_13 = allwinner.PH9  //
	P1_14 = pin.GROUND     //
	P1_15 = allwinner.PC12 //
	P1_16 = allwinner.PC13 //
	P1_17 = pin.V3_3       //
	P1_18 = allwinner.PC14 //
	P1_19 = allwinner.PC0  //
	P1_20 = pin.GROUND     //
	P1_21 = allwinner.PC1  //
	P1_22 = allwinner.PC15 //
	P1_23 = allwinner.PC2  //
	P1_24 = allwinner.PC3  //
	P1_25 = pin.GROUND     //
	P1_26 = allwinner.PH7  //
	P1_27 = allwinner.PL9  //
	P1_28 = allwinner.PL8  //
	P1_29 = allwinner.PH5  //
	P1_30 = pin.GROUND     //
	P1_31 = allwinner.PH6  //
	P1_32 = allwinner.PC4  //
	P1_33 = allwinner.PC5  //
	P1_34 = pin.GROUND     //
	P1_35 = allwinner.PC9  //
	P1_36 = allwinner.PC6  //
	P1_37 = allwinner.PC16 //
	P1_38 = allwinner.PC10 //
	P1_39 = pin.GROUND     //
	P1_40 = allwinner.PC11 //

	EULER_1  = pin.V3_3          //
	EULER_2  = pin.DC_IN         //
	EULER_3  = pin.BAT_PLUS      //
	EULER_4  = pin.DC_IN         //
	EULER_5  = TEMP_SENSOR       //
	EULER_6  = pin.GROUND        //
	EULER_7  = IR_RX             //
	EULER_8  = pin.V5            //
	EULER_9  = pin.GROUND        //
	EULER_10 = allwinner.PH8     //
	EULER_11 = allwinner.PB3     //
	EULER_12 = allwinner.PB4     //
	EULER_13 = allwinner.PB5     //
	EULER_14 = pin.GROUND        //
	EULER_15 = allwinner.PB6     //
	EULER_16 = allwinner.PB7     //
	EULER_17 = pin.V3_3          //
	EULER_18 = allwinner.PD4     //
	EULER_19 = allwinner.PD2     //
	EULER_20 = pin.GROUND        //
	EULER_21 = allwinner.PD3     //
	EULER_22 = allwinner.PD5     //
	EULER_23 = allwinner.PD1     //
	EULER_24 = allwinner.PD0     //
	EULER_25 = pin.GROUND        //
	EULER_26 = allwinner.PD6     //
	EULER_27 = allwinner.PB2     //
	EULER_28 = allwinner.PD7     //
	EULER_29 = allwinner.PB8     //
	EULER_30 = allwinner.PB9     //
	EULER_31 = allwinner.EAROUTP //
	EULER_32 = allwinner.EAROUTN //
	EULER_33 = pin.INVALID       //
	EULER_34 = pin.GROUND        //

	EXP_1  = pin.V3_3          //
	EXP_2  = allwinner.PL7     //
	EXP_3  = CHARGER_LED       //
	EXP_4  = RESET             //
	EXP_5  = PWR_SWITCH        //
	EXP_6  = pin.GROUND        //
	EXP_7  = allwinner.PB8     //
	EXP_8  = allwinner.PB9     //
	EXP_9  = pin.GROUND        //
	EXP_10 = allwinner.KEY_ADC //

	WIFI_BT_1  = pin.GROUND         //
	WIFI_BT_2  = allwinner.PG6      //
	WIFI_BT_3  = allwinner.PG0      //
	WIFI_BT_4  = allwinner.PG7      //
	WIFI_BT_5  = pin.GROUND         //
	WIFI_BT_6  = allwinner.PG8      //
	WIFI_BT_7  = allwinner.PG1      //
	WIFI_BT_8  = allwinner.PG9      //
	WIFI_BT_9  = allwinner.PG2      //
	WIFI_BT_10 = allwinner.PG10     //
	WIFI_BT_11 = allwinner.PG3      //
	WIFI_BT_12 = allwinner.PG11     //
	WIFI_BT_13 = allwinner.PG4      //
	WIFI_BT_14 = allwinner.PG12     //
	WIFI_BT_15 = allwinner.PG5      //
	WIFI_BT_16 = allwinner.PG13     //
	WIFI_BT_17 = allwinner.PL2      //
	WIFI_BT_18 = pin.GROUND         //
	WIFI_BT_19 = allwinner.PL3      //
	WIFI_BT_20 = allwinner.PL5      //
	WIFI_BT_21 = allwinner.X32KFOUT //
	WIFI_BT_22 = allwinner.PL5      //
	WIFI_BT_23 = pin.GROUND         //
	WIFI_BT_24 = allwinner.PL6      //
	WIFI_BT_25 = VCC                //
	WIFI_BT_26 = IOVCC              //

	AUDIO_LEFT  = pin.INVALID // BUG(maruel): Fix once analog is implemented.
	AUDIO_RIGHT = pin.INVALID //
)

//

// driver implements periph.Driver.
type driver struct {
}

func (d *driver) String() string {
	return "pine64"
}

func (d *driver) Prerequisites() []string {
	return nil
}

func (d *driver) After() []string {
	return []string{"allwinner-gpio", "allwinner-gpio-pl"}
}

func (d *driver) Init() (bool, error) {
	if !Present() {
		return false, errors.New("pine64 board not detected")
	}
	if err := pinreg.Register("P1", [][]pin.Pin{
		{P1_1, P1_2},
		{P1_3, P1_4},
		{P1_5, P1_6},
		{P1_7, P1_8},
		{P1_9, P1_10},
		{P1_11, P1_12},
		{P1_13, P1_14},
		{P1_15, P1_16},
		{P1_17, P1_18},
		{P1_19, P1_20},
		{P1_21, P1_22},
		{P1_23, P1_24},
		{P1_25, P1_26},
		{P1_27, P1_28},
		{P1_29, P1_30},
		{P1_31, P1_32},
		{P1_33, P1_34},
		{P1_35, P1_36},
		{P1_37, P1_38},
		{P1_39, P1_40},
	}); err != nil {
		return true, err
	}
	if err := pinreg.Register("EULER", [][]pin.Pin{
		{EULER_1, EULER_2},
		{EULER_3, EULER_4},
		{EULER_5, EULER_6},
		{EULER_7, EULER_8},
		{EULER_9, EULER_10},
		{EULER_11, EULER_12},
		{EULER_13, EULER_14},
		{EULER_15, EULER_16},
		{EULER_17, EULER_18},
		{EULER_19, EULER_20},
		{EULER_21, EULER_22},
		{EULER_23, EULER_24},
		{EULER_25, EULER_26},
		{EULER_27, EULER_28},
		{EULER_29, EULER_30},
		{EULER_31, EULER_32},
		{EULER_33, EULER_34},
	}); err != nil {
		return true, err
	}

	if err := pinreg.Register("EXP", [][]pin.Pin{
		{EXP_1, EXP_2},
		{EXP_3, EXP_4},
		{EXP_5, EXP_6},
		{EXP_7, EXP_8},
		{EXP_9, EXP_10},
	}); err != nil {
		return true, err
	}

	if err := pinreg.Register("WIFI_BT", [][]pin.Pin{
		{WIFI_BT_1, WIFI_BT_2},
		{WIFI_BT_3, WIFI_BT_4},
		{WIFI_BT_5, WIFI_BT_6},
		{WIFI_BT_7, WIFI_BT_8},
		{WIFI_BT_9, WIFI_BT_10},
		{WIFI_BT_11, WIFI_BT_12},
		{WIFI_BT_13, WIFI_BT_14},
		{WIFI_BT_15, WIFI_BT_16},
		{WIFI_BT_17, WIFI_BT_18},
		{WIFI_BT_19, WIFI_BT_20},
		{WIFI_BT_21, WIFI_BT_22},
		{WIFI_BT_23, WIFI_BT_24},
		{WIFI_BT_25, WIFI_BT_26},
	}); err != nil {
		return true, err
	}

	if err := pinreg.Register("AUDIO", [][]pin.Pin{
		{AUDIO_LEFT},
		{AUDIO_RIGHT},
	}); err != nil {
		return true, err
	}

	return true, nil
}

func init() {
	if isArm {
		periph.MustRegister(&drv)
	}
}

var drv driver
<commit_msg>host/pine64: improve detection (#454)<commit_after>// Copyright 2016 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

package pine64

import (
	"errors"
	"strings"

	"periph.io/x/periph"
	"periph.io/x/periph/conn/pin"
	"periph.io/x/periph/conn/pin/pinreg"
	"periph.io/x/periph/host/allwinner"
	"periph.io/x/periph/host/distro"
)

// Present returns true if running on a Pine64 board.
//
// https://www.pine64.org/
func Present() bool {
	if isArm {
		return strings.HasPrefix(distro.DTModel(), "Pine64")
	}
	return false
}

// Pine64 specific pins.
var (
	VCC         = &pin.BasicPin{N: "VCC"}         //
	IOVCC       = &pin.BasicPin{N: "IOVCC"}       // Power supply for port A
	TEMP_SENSOR = &pin.BasicPin{N: "TEMP_SENSOR"} //
	IR_RX       = &pin.BasicPin{N: "IR_RX"}       // IR Data Receive
	CHARGER_LED = &pin.BasicPin{N: "CHARGER_LED"} //
	RESET       = &pin.BasicPin{N: "RESET"}       //
	PWR_SWITCH  = &pin.BasicPin{N: "PWR_SWITCH "} //
)

// All the individual pins on the headers.
var (
	P1_1  = pin.V3_3       // max 40mA
	P1_2  = pin.V5         // (filtered)
	P1_3  = allwinner.PH3  //
	P1_4  = pin.V5         // (filtered)
	P1_5  = allwinner.PH2  //
	P1_6  = pin.GROUND     //
	P1_7  = allwinner.PL10 //
	P1_8  = allwinner.PB0  //
	P1_9  = pin.GROUND     //
	P1_10 = allwinner.PB1  //
	P1_11 = allwinner.PC7  //
	P1_12 = allwinner.PC8  //
	P1_13 = allwinner.PH9  //
	P1_14 = pin.GROUND     //
	P1_15 = allwinner.PC12 //
	P1_16 = allwinner.PC13 //
	P1_17 = pin.V3_3       //
	P1_18 = allwinner.PC14 //
	P1_19 = allwinner.PC0  //
	P1_20 = pin.GROUND     //
	P1_21 = allwinner.PC1  //
	P1_22 = allwinner.PC15 //
	P1_23 = allwinner.PC2  //
	P1_24 = allwinner.PC3  //
	P1_25 = pin.GROUND     //
	P1_26 = allwinner.PH7  //
	P1_27 = allwinner.PL9  //
	P1_28 = allwinner.PL8  //
	P1_29 = allwinner.PH5  //
	P1_30 = pin.GROUND     //
	P1_31 = allwinner.PH6  //
	P1_32 = allwinner.PC4  //
	P1_33 = allwinner.PC5  //
	P1_34 = pin.GROUND     //
	P1_35 = allwinner.PC9  //
	P1_36 = allwinner.PC6  //
	P1_37 = allwinner.PC16 //
	P1_38 = allwinner.PC10 //
	P1_39 = pin.GROUND     //
	P1_40 = allwinner.PC11 //

	EULER_1  = pin.V3_3          //
	EULER_2  = pin.DC_IN         //
	EULER_3  = pin.BAT_PLUS      //
	EULER_4  = pin.DC_IN         //
	EULER_5  = TEMP_SENSOR       //
	EULER_6  = pin.GROUND        //
	EULER_7  = IR_RX             //
	EULER_8  = pin.V5            //
	EULER_9  = pin.GROUND        //
	EULER_10 = allwinner.PH8     //
	EULER_11 = allwinner.PB3     //
	EULER_12 = allwinner.PB4     //
	EULER_13 = allwinner.PB5     //
	EULER_14 = pin.GROUND        //
	EULER_15 = allwinner.PB6     //
	EULER_16 = allwinner.PB7     //
	EULER_17 = pin.V3_3          //
	EULER_18 = allwinner.PD4     //
	EULER_19 = allwinner.PD2     //
	EULER_20 = pin.GROUND        //
	EULER_21 = allwinner.PD3     //
	EULER_22 = allwinner.PD5     //
	EULER_23 = allwinner.PD1     //
	EULER_24 = allwinner.PD0     //
	EULER_25 = pin.GROUND        //
	EULER_26 = allwinner.PD6     //
	EULER_27 = allwinner.PB2     //
	EULER_28 = allwinner.PD7     //
	EULER_29 = allwinner.PB8     //
	EULER_30 = allwinner.PB9     //
	EULER_31 = allwinner.EAROUTP //
	EULER_32 = allwinner.EAROUTN //
	EULER_33 = pin.INVALID       //
	EULER_34 = pin.GROUND        //

	EXP_1  = pin.V3_3          //
	EXP_2  = allwinner.PL7     //
	EXP_3  = CHARGER_LED       //
	EXP_4  = RESET             //
	EXP_5  = PWR_SWITCH        //
	EXP_6  = pin.GROUND        //
	EXP_7  = allwinner.PB8     //
	EXP_8  = allwinner.PB9     //
	EXP_9  = pin.GROUND        //
	EXP_10 = allwinner.KEY_ADC //

	WIFI_BT_1  = pin.GROUND         //
	WIFI_BT_2  = allwinner.PG6      //
	WIFI_BT_3  = allwinner.PG0      //
	WIFI_BT_4  = allwinner.PG7      //
	WIFI_BT_5  = pin.GROUND         //
	WIFI_BT_6  = allwinner.PG8      //
	WIFI_BT_7  = allwinner.PG1      //
	WIFI_BT_8  = allwinner.PG9      //
	WIFI_BT_9  = allwinner.PG2      //
	WIFI_BT_10 = allwinner.PG10     //
	WIFI_BT_11 = allwinner.PG3      //
	WIFI_BT_12 = allwinner.PG11     //
	WIFI_BT_13 = allwinner.PG4      //
	WIFI_BT_14 = allwinner.PG12     //
	WIFI_BT_15 = allwinner.PG5      //
	WIFI_BT_16 = allwinner.PG13     //
	WIFI_BT_17 = allwinner.PL2      //
	WIFI_BT_18 = pin.GROUND         //
	WIFI_BT_19 = allwinner.PL3      //
	WIFI_BT_20 = allwinner.PL5      //
	WIFI_BT_21 = allwinner.X32KFOUT //
	WIFI_BT_22 = allwinner.PL5      //
	WIFI_BT_23 = pin.GROUND         //
	WIFI_BT_24 = allwinner.PL6      //
	WIFI_BT_25 = VCC                //
	WIFI_BT_26 = IOVCC              //

	AUDIO_LEFT  = pin.INVALID // BUG(maruel): Fix once analog is implemented.
	AUDIO_RIGHT = pin.INVALID //
)

//

// driver implements periph.Driver.
type driver struct {
}

func (d *driver) String() string {
	return "pine64"
}

func (d *driver) Prerequisites() []string {
	return nil
}

func (d *driver) After() []string {
	return []string{"allwinner-gpio", "allwinner-gpio-pl"}
}

func (d *driver) Init() (bool, error) {
	if !Present() {
		return false, errors.New("pine64 board not detected")
	}
	if err := pinreg.Register("P1", [][]pin.Pin{
		{P1_1, P1_2},
		{P1_3, P1_4},
		{P1_5, P1_6},
		{P1_7, P1_8},
		{P1_9, P1_10},
		{P1_11, P1_12},
		{P1_13, P1_14},
		{P1_15, P1_16},
		{P1_17, P1_18},
		{P1_19, P1_20},
		{P1_21, P1_22},
		{P1_23, P1_24},
		{P1_25, P1_26},
		{P1_27, P1_28},
		{P1_29, P1_30},
		{P1_31, P1_32},
		{P1_33, P1_34},
		{P1_35, P1_36},
		{P1_37, P1_38},
		{P1_39, P1_40},
	}); err != nil {
		return true, err
	}
	if err := pinreg.Register("EULER", [][]pin.Pin{
		{EULER_1, EULER_2},
		{EULER_3, EULER_4},
		{EULER_5, EULER_6},
		{EULER_7, EULER_8},
		{EULER_9, EULER_10},
		{EULER_11, EULER_12},
		{EULER_13, EULER_14},
		{EULER_15, EULER_16},
		{EULER_17, EULER_18},
		{EULER_19, EULER_20},
		{EULER_21, EULER_22},
		{EULER_23, EULER_24},
		{EULER_25, EULER_26},
		{EULER_27, EULER_28},
		{EULER_29, EULER_30},
		{EULER_31, EULER_32},
		{EULER_33, EULER_34},
	}); err != nil {
		return true, err
	}

	if err := pinreg.Register("EXP", [][]pin.Pin{
		{EXP_1, EXP_2},
		{EXP_3, EXP_4},
		{EXP_5, EXP_6},
		{EXP_7, EXP_8},
		{EXP_9, EXP_10},
	}); err != nil {
		return true, err
	}

	if err := pinreg.Register("WIFI_BT", [][]pin.Pin{
		{WIFI_BT_1, WIFI_BT_2},
		{WIFI_BT_3, WIFI_BT_4},
		{WIFI_BT_5, WIFI_BT_6},
		{WIFI_BT_7, WIFI_BT_8},
		{WIFI_BT_9, WIFI_BT_10},
		{WIFI_BT_11, WIFI_BT_12},
		{WIFI_BT_13, WIFI_BT_14},
		{WIFI_BT_15, WIFI_BT_16},
		{WIFI_BT_17, WIFI_BT_18},
		{WIFI_BT_19, WIFI_BT_20},
		{WIFI_BT_21, WIFI_BT_22},
		{WIFI_BT_23, WIFI_BT_24},
		{WIFI_BT_25, WIFI_BT_26},
	}); err != nil {
		return true, err
	}

	if err := pinreg.Register("AUDIO", [][]pin.Pin{
		{AUDIO_LEFT},
		{AUDIO_RIGHT},
	}); err != nil {
		return true, err
	}

	return true, nil
}

func init() {
	if isArm {
		periph.MustRegister(&drv)
	}
}

var drv driver
<|endoftext|>


<commit_before>package dsl

import (
	"goa.design/goa/v3/eval"
	"goa.design/goa/v3/expr"
)

// Description sets the expression description.
//
// Description may appear in API, Docs, Type or Attribute.
// Description may also appear in Response and FileServer.
//
// Description accepts one arguments: the description string.
//
// Example:
//
//    API("adder", func() {
//        Description("Adder API")
//    })
//
func Description(d string) {
	switch e := eval.Current().(type) {
	case *expr.APIExpr:
		e.Description = d
	case *expr.ServerExpr:
		e.Description = d
	case *expr.HostExpr:
		e.Description = d
	case *expr.ServiceExpr:
		e.Description = d
	case *expr.ResultTypeExpr:
		e.Description = d
	case *expr.AttributeExpr:
		e.Description = d
	case *expr.DocsExpr:
		e.Description = d
	case *expr.MethodExpr:
		e.Description = d
	case *expr.ExampleExpr:
		e.Description = d
	case *expr.SchemeExpr:
		e.Description = d
	case *expr.HTTPResponseExpr:
		e.Description = d
	case *expr.HTTPFileServerExpr:
		e.Description = d
	case *expr.GRPCResponseExpr:
		e.Description = d
	default:
		eval.IncompatibleDSL()
	}
}
<commit_msg>Fix dsl.Description doc comment (#2318)<commit_after>package dsl

import (
	"goa.design/goa/v3/eval"
	"goa.design/goa/v3/expr"
)

// Description sets the expression description.
//
// Description may appear in API, Docs, Type or Attribute.
// Description may also appear in Response and Files.
//
// Description accepts one arguments: the description string.
//
// Example:
//
//    API("adder", func() {
//        Description("Adder API")
//    })
//
func Description(d string) {
	switch e := eval.Current().(type) {
	case *expr.APIExpr:
		e.Description = d
	case *expr.ServerExpr:
		e.Description = d
	case *expr.HostExpr:
		e.Description = d
	case *expr.ServiceExpr:
		e.Description = d
	case *expr.ResultTypeExpr:
		e.Description = d
	case *expr.AttributeExpr:
		e.Description = d
	case *expr.DocsExpr:
		e.Description = d
	case *expr.MethodExpr:
		e.Description = d
	case *expr.ExampleExpr:
		e.Description = d
	case *expr.SchemeExpr:
		e.Description = d
	case *expr.HTTPResponseExpr:
		e.Description = d
	case *expr.HTTPFileServerExpr:
		e.Description = d
	case *expr.GRPCResponseExpr:
		e.Description = d
	default:
		eval.IncompatibleDSL()
	}
}
<|endoftext|>


<commit_before>package stack

import (
	"bytes"
	"io"
	"log"
	"net/http"
	"os"
	"sync"
	"time"

	"github.com/reflexionhealth/vanilla/httpserver"
)

const (
	AnsiBlack   = "\x1b[30m"
	AnsiRed     = "\x1b[31m"
	AnsiGreen   = "\x1b[32m"
	AnsiYellow  = "\x1b[33m"
	AnsiBlue    = "\x1b[34m"
	AnsiMagenta = "\x1b[35m"
	AnsiCyan    = "\x1b[36m"
	AnsiWhite   = "\x1b[37m"

	AnsiReset = "\x1b[0m"
	AnsiBold  = "\x1b[1m"

	LogTimeFormat = "2006/01/02 - 15:04:05"
)

var Logger = NewStackLogger(os.Stdout)

// StackLogger stores log output in memory for a given request context so that log
// output for the given request is sequential in the final log.
// This makes it easier to gobble up all the information for a single request with Logstash.
type StackLogger struct {
	Global *log.Logger
	Pool   sync.Pool
}

func NewStackLogger(out io.Writer) *StackLogger {
	logger := &StackLogger{log.New(out, "", 0), sync.Pool{}}
	logger.Pool.New = newRequestLog
	return logger
}

type RequestLog struct {
	*log.Logger
	Buffer *bytes.Buffer
}

func newRequestLog() interface{} {
	buffer := &bytes.Buffer{}
	return &RequestLog{log.New(buffer, "", 0), buffer}
}

func (l *StackLogger) Logf(c *httpserver.Context, format string, args ...interface{}) {
	logPtr, exists := c.GetLocal("Log")
	if exists {
		logger := logPtr.(*RequestLog)
		logger.Printf(format, args...)
	} else {
		Logger.Global.Printf(format, args...)
	}
}

func (l *StackLogger) LogValue(c *httpserver.Context, name string, value interface{}) {
	logPtr, exists := c.GetLocal("Log")
	if exists {
		logger := logPtr.(*RequestLog)
		if c.Debug {
			logger.Printf(" -- %s%s:%s %v\n", AnsiBold, name, AnsiReset, value)
		} else {
			logger.Printf(" -- %s: %v\n", name, value)
		}
	} else {
		// LogValue should only be called after the LogRequest middleware,
		// Print out a [?] if we don't have a "Log" local
		if c.Debug {
			Logger.Global.Printf("[?] %s%s:%s %v\n", AnsiBold, name, AnsiReset, value)
		} else {
			Logger.Global.Printf("[?] %s: %v\n", name, value)
		}
	}
}

func (l *StackLogger) LogResponse(c *httpserver.Context, status string, value interface{}) {
	logPtr, exists := c.GetLocal("Log")
	if exists {
		logger := logPtr.(*RequestLog)
		if c.Debug {
			logger.Printf(" -> %s%s:%s %v\n", AnsiBold, status, AnsiReset, value)
		} else {
			logger.Printf(" -> %s: %v\n", status, value)
		}
	} else {
		// LogValue should only be called after the LogRequest middleware,
		// Print out a [?] if we don't have a "Log" local
		if c.Debug {
			Logger.Global.Printf("[?] %s%s:%s %v\n", AnsiBold, status, AnsiReset, value)
		} else {
			Logger.Global.Printf("[?] %s: %v\n", status, value)
		}
	}
}

func LogRequest(c *httpserver.Context) {
	start := time.Now()
	path := c.Request.URL.Path
	method := c.Request.Method
	clientIP := c.ClientIP()

	// Always immediately log that we received a request, in case the request takes a long time
	Logger.Global.Printf("Received %s \"%s\" from %s at %v\n", method, path, clientIP, start.Format(LogTimeFormat))

	// Log preamble
	request := Logger.Pool.Get().(*RequestLog)
	request.Buffer.Reset()
	request.Printf("Log for %s \"%s\" from %s at %v\n", method, path, clientIP, start.Format(LogTimeFormat))
	defer Logger.Pool.Put(request)

	c.SetLocal("Log", request)
	defer delete(c.Locals, "Log")

	// Log headers we care about
	headers := []string{"Accept", "Reflexion-Application"}
	for _, header := range headers {
		value := c.Request.Header.Get(header)
		if len(value) > 0 {
			if len(value) <= 60 {
				Logger.LogValue(c, header, value)
			} else {
				Logger.LogValue(c, header, value[:56]+" ...")
			}
		}
	}

	// Handle request
	c.PerformRequest()

	// Log postamble
	end := time.Now()
	latency := end.Sub(start)
	statusCode := c.Response.Status()
	statusText := http.StatusText(statusCode)
	if c.Debug {
		statusColor := colorForStatus(statusCode)
		request.Printf("Replied with %s%d %s%s in %v\n", statusColor, statusCode, statusText, AnsiReset, latency)
	} else {
		request.Printf("Replied with %d %s in %v\n", statusCode, statusText, latency)
	}

	// Write log
	Logger.Global.Print(request.Buffer.String())
}

func colorForStatus(code int) string {
	switch {
	case code >= 100 && code < 200:
		return AnsiBlue
	case code >= 200 && code < 300:
		return AnsiGreen
	case code >= 300 && code < 400:
		return AnsiGreen
	case code >= 400 && code < 500:
		return AnsiYellow
	default:
		return AnsiRed
	}
}
<commit_msg>httpserver/stack: add simple logger<commit_after>package stack

import (
	"bytes"
	"io"
	"log"
	"net/http"
	"os"
	"sync"
	"time"

	"github.com/reflexionhealth/vanilla/httpserver"
)

const (
	AnsiBlack   = "\x1b[30m"
	AnsiRed     = "\x1b[31m"
	AnsiGreen   = "\x1b[32m"
	AnsiYellow  = "\x1b[33m"
	AnsiBlue    = "\x1b[34m"
	AnsiMagenta = "\x1b[35m"
	AnsiCyan    = "\x1b[36m"
	AnsiWhite   = "\x1b[37m"

	AnsiReset = "\x1b[0m"
	AnsiBold  = "\x1b[1m"

	LogTimeFormat = "2006/01/02 - 15:04:05"
)

var Logger = NewStackLogger(os.Stdout)

// StackLogger stores log output in memory for a given request context so that log
// output for the given request is sequential in the final log.
// This makes it easier to gobble up all the information for a single request with Logstash.
type StackLogger struct {
	Global *log.Logger
	Pool   sync.Pool
}

func NewStackLogger(out io.Writer) *StackLogger {
	logger := &StackLogger{log.New(out, "", 0), sync.Pool{}}
	logger.Pool.New = newRequestLog
	return logger
}

type RequestLog struct {
	*log.Logger
	Buffer *bytes.Buffer
}

func newRequestLog() interface{} {
	buffer := &bytes.Buffer{}
	return &RequestLog{log.New(buffer, "", 0), buffer}
}

func (l *StackLogger) Logf(c *httpserver.Context, format string, args ...interface{}) {
	logPtr, exists := c.GetLocal("Log")
	if exists {
		logger := logPtr.(*RequestLog)
		logger.Printf(format, args...)
	} else {
		Logger.Global.Printf(format, args...)
	}
}

func (l *StackLogger) LogValue(c *httpserver.Context, name string, value interface{}) {
	logPtr, exists := c.GetLocal("Log")
	if exists {
		logger := logPtr.(*RequestLog)
		if c.Debug {
			logger.Printf(" -- %s%s:%s %v\n", AnsiBold, name, AnsiReset, value)
		} else {
			logger.Printf(" -- %s: %v\n", name, value)
		}
	} else {
		// LogValue should only be called after the LogRequest middleware,
		// Print out a [?] if we don't have a "Log" local
		if c.Debug {
			Logger.Global.Printf("[?] %s%s:%s %v\n", AnsiBold, name, AnsiReset, value)
		} else {
			Logger.Global.Printf("[?] %s: %v\n", name, value)
		}
	}
}

func (l *StackLogger) LogResponse(c *httpserver.Context, status string, value interface{}) {
	logPtr, exists := c.GetLocal("Log")
	if exists {
		logger := logPtr.(*RequestLog)
		if c.Debug {
			logger.Printf(" -> %s%s:%s %v\n", AnsiBold, status, AnsiReset, value)
		} else {
			logger.Printf(" -> %s: %v\n", status, value)
		}
	} else {
		// LogValue should only be called after the LogRequest middleware,
		// Print out a [?] if we don't have a "Log" local
		if c.Debug {
			Logger.Global.Printf("[?] %s%s:%s %v\n", AnsiBold, status, AnsiReset, value)
		} else {
			Logger.Global.Printf("[?] %s: %v\n", status, value)
		}
	}
}

func LogAccess(c *httpserver.Context) {
	now := time.Now().Format(LogTimeFormat)
	path := c.Request.URL.Path
	method := c.Request.Method
	clientIP := c.ClientIP()

	Logger.Global.Printf("Received %s \"%s\" from %s at %v\n", method, path, clientIP, now)
	c.ContinueRequest()
}

func LogRequest(c *httpserver.Context) {
	start := time.Now()
	path := c.Request.URL.Path
	method := c.Request.Method
	clientIP := c.ClientIP()

	// Always immediately log that we received a request, in case the request takes a long time
	Logger.Global.Printf("Received %s \"%s\" from %s at %v\n", method, path, clientIP, start.Format(LogTimeFormat))

	// Log preamble
	request := Logger.Pool.Get().(*RequestLog)
	request.Buffer.Reset()
	request.Printf("Log for %s \"%s\" from %s at %v\n", method, path, clientIP, start.Format(LogTimeFormat))
	defer Logger.Pool.Put(request)

	c.SetLocal("Log", request)
	defer delete(c.Locals, "Log")

	// Log headers we care about
	headers := []string{"Accept", "Reflexion-Application"}
	for _, header := range headers {
		value := c.Request.Header.Get(header)
		if len(value) > 0 {
			if len(value) <= 60 {
				Logger.LogValue(c, header, value)
			} else {
				Logger.LogValue(c, header, value[:56]+" ...")
			}
		}
	}

	// Handle request
	c.PerformRequest()

	// Log postamble
	end := time.Now()
	latency := end.Sub(start)
	statusCode := c.Response.Status()
	statusText := http.StatusText(statusCode)
	if c.Debug {
		statusColor := colorForStatus(statusCode)
		request.Printf("Replied with %s%d %s%s in %v\n", statusColor, statusCode, statusText, AnsiReset, latency)
	} else {
		request.Printf("Replied with %d %s in %v\n", statusCode, statusText, latency)
	}

	// Write log
	Logger.Global.Print(request.Buffer.String())
}

func colorForStatus(code int) string {
	switch {
	case code >= 100 && code < 200:
		return AnsiBlue
	case code >= 200 && code < 300:
		return AnsiGreen
	case code >= 300 && code < 400:
		return AnsiGreen
	case code >= 400 && code < 500:
		return AnsiYellow
	default:
		return AnsiRed
	}
}
<|endoftext|>


<commit_before>// Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package assert provides assert helper functions for testing package.

Example:

	package assert_test

	import (
		"image"
		"math"
		"strings"
		"testing"

		. "github.com/chai2010/assert.go"
	)

	func TestAssert(t *testing.T) {
		Assert(t, 1 == 1)
		Assert(t, 1 == 1, "message1", "message2")
	}

	func TestAssertTrue(t *testing.T) {
		AssertTrue(t, true)
	}

	func TestAssertFalse(t *testing.T) {
		AssertFalse(t, false)
	}

	func TestAssertEqual(t *testing.T) {
		AssertEqual(t, 2, 1+1)
		AssertEqual(t, "abc", strings.ToLower("ABC"))
		AssertEqual(t, image.Pt(1, 2), image.Pt(1, 2))
	}

	func TestAssertNotEqual(t *testing.T) {
		AssertNotEqual(t, 2, 1)
		AssertNotEqual(t, "ABC", strings.ToLower("ABC"))
		AssertNotEqual(t, image.Pt(1, 2), image.Pt(2, 2))
		AssertNotEqual(t, image.Pt(1, 2), image.Rect(1, 2, 3, 4))
	}

	func TestAssertNear(t *testing.T) {
		AssertNear(t, 1.414, math.Sqrt(2), 0.1)
	}

	func TestAssertBetween(t *testing.T) {
		AssertBetween(t, 0, 255, 0)
		AssertBetween(t, 0, 255, 128)
		AssertBetween(t, 0, 255, 255)
	}

	func TestAssertNotBetween(t *testing.T) {
		AssertNotBetween(t, 0, 255, -1)
		AssertNotBetween(t, 0, 255, 256)
	}

	func TestAssertMatch(t *testing.T) {
		AssertMatch(t, `^\w+@\w+\.com$`, "chaishushan@gmail.com")
		AssertMatch(t, `^assert`, "assert.go")
		AssertMatch(t, `\.go$`, "assert.go")
	}

	func TestAssertSliceContain(t *testing.T) {
		AssertSliceContain(t, []int{1, 1, 2, 3, 5, 8, 13}, 8)
		AssertSliceContain(t, []interface{}{1, 1, 2, 3, 5, "8", 13}, "8")
	}

	func TestAssertSliceNotContain(t *testing.T) {
		AssertSliceNotContain(t, []int{1, 1, 2, 3, 5, 8, 13}, 12)
		AssertSliceNotContain(t, []interface{}{1, 1, 2, 3, 5, "8", 13}, 8)
	}

	func TestAssertMapContain(t *testing.T) {
		AssertMapContain(t,
			map[string]int{
				"UTC": 0 * 60 * 60,
				"EST": -5 * 60 * 60,
				"CST": -6 * 60 * 60,
				"MST": -7 * 60 * 60,
				"PST": -8 * 60 * 60,
			},
			"MST", -7*60*60,
		)
	}

	func TestAssertMapNotContain(t *testing.T) {
		AssertMapNotContain(t,
			map[string]int{
				"UTC": 0 * 60 * 60,
				"EST": -5 * 60 * 60,
				"CST": -6 * 60 * 60,
				"MST": -7 * 60 * 60,
				"PST": -8 * 60 * 60,
			},
			"ABC", -7*60*60,
		)
	}

	func TestAssertZero(t *testing.T) {
		AssertZero(t, struct {
			A bool
			B string
			C int
			d map[string]interface{}
		}{})
	}

	func TestAssertNotZero(t *testing.T) {
		AssertNotZero(t, struct {
			A bool
			B string
			C int
			d map[string]interface{}
		}{A: true})
	}

	func TestAssertFileExists(t *testing.T) {
		AssertFileExists(t, "assert.go")
	}

	func TestAssertFileNotExists(t *testing.T) {
		AssertFileNotExists(t, "assert.cc")
	}

Report bugs to <chaishushan@gmail.com>.

Thanks!
*/
package assert

import (
	"fmt"
	"math"
	"os"
	"reflect"
	"regexp"
	"testing"
)

func Assert(t testing.TB, condition bool, args ...interface{}) {
	if !condition {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("Assert failed, %s", msg)
		} else {
			t.Fatal("Assert failed")
		}
	}
}

func AssertTrue(t testing.TB, condition bool, args ...interface{}) {
	if condition != true {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertTrue failed, %s", msg)
		} else {
			t.Fatal("AssertTrue failed")
		}
	}
}

func AssertFalse(t testing.TB, condition bool, args ...interface{}) {
	if condition != false {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertFalse failed, %s", msg)
		} else {
			t.Fatal("AssertFalse failed")
		}
	}
}

func AssertEqual(t testing.TB, expected, got interface{}, args ...interface{}) {
	if !reflect.DeepEqual(expected, got) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertEqual failed, expected = %v, got = %v, %s", expected, got, msg)
		} else {
			t.Fatalf("AssertEqual failed, expected = %v, got = %v", expected, got)
		}
	}
}

func AssertNotEqual(t testing.TB, expected, got interface{}, args ...interface{}) {
	if reflect.DeepEqual(expected, got) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNotEqual failed, expected = %v, got = %v, %s", expected, got, msg)
		} else {
			t.Fatalf("AssertNotEqual failed, expected = %v, got = %v", expected, got)
		}
	}
}

func AssertNear(t testing.TB, expected, got, abs float64, args ...interface{}) {
	if math.Abs(expected-got) > abs {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNear failed, expected = %v, got = %v, abs = %v, %s", expected, got, abs, msg)
		} else {
			t.Fatalf("AssertNear failed, expected = %v, got = %v, abs = %v", expected, got, abs)
		}
	}
}

func AssertBetween(t testing.TB, min, max, val float64, args ...interface{}) {
	if val < min || max < val {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertBetween failed, min = %v, max = %v, val = %v, %s", min, max, val, msg)
		} else {
			t.Fatalf("AssertBetween failed, min = %v, max = %v, val = %v", min, max, val)
		}
	}
}

func AssertNotBetween(t testing.TB, min, max, val float64, args ...interface{}) {
	if min <= val && val <= max {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNotBetween failed, min = %v, max = %v, val = %v, %s", min, max, val, msg)
		} else {
			t.Fatalf("AssertNotBetween failed, min = %v, max = %v, val = %v", min, max, val)
		}
	}
}

func AssertMatch(t *testing.T, expectedPattern, got string, args ...interface{}) {
	if matched, err := regexp.MatchString(expectedPattern, got); err != nil || !matched {
		if err != nil {
			if msg := fmt.Sprint(args...); msg != "" {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v, err = %v, %s", expectedPattern, got, err, msg)
			} else {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v, err = %v", expectedPattern, got, err)
			}
		} else {
			if msg := fmt.Sprint(args...); msg != "" {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v, %s", expectedPattern, got, msg)
			} else {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v", expectedPattern, got)
			}
		}
	}
}

func AssertSliceContain(t *testing.T, slice, elem interface{}, args ...interface{}) {
	sliceVal := reflect.ValueOf(slice)
	if sliceVal.Kind() != reflect.Slice {
		panic(fmt.Sprintf("AssertSliceContain called with non-slice value of type %T", slice))
	}
	var contained bool
	for i := 0; i < sliceVal.Len(); i++ {
		if reflect.DeepEqual(sliceVal.Index(i).Interface(), elem) {
			contained = true
			break
		}
	}
	if !contained {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertSliceContain failed, slice = %v, elem = %v, %s", slice, elem, msg)
		} else {
			t.Fatalf("AssertSliceContain failed, slice = %v, elem = %v", slice, elem)
		}
	}
}

func AssertSliceNotContain(t *testing.T, slice, elem interface{}, args ...interface{}) {
	sliceVal := reflect.ValueOf(slice)
	if sliceVal.Kind() != reflect.Slice {
		panic(fmt.Sprintf("AssertSliceNotContain called with non-slice value of type %T", slice))
	}
	var contained bool
	for i := 0; i < sliceVal.Len(); i++ {
		if reflect.DeepEqual(sliceVal.Index(i).Interface(), elem) {
			contained = true
			break
		}
	}
	if contained {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertSliceNotContain failed, slice = %v, elem = %v, %s", slice, elem, msg)
		} else {
			t.Fatalf("AssertSliceNotContain failed, slice = %v, elem = %v", slice, elem)
		}
	}
}

func AssertMapContain(t *testing.T, m, key, elem interface{}, args ...interface{}) {
	mapVal := reflect.ValueOf(m)
	if mapVal.Kind() != reflect.Map {
		panic(fmt.Sprintf("AssertMapContain called with non-map value of type %T", m))
	}
	elemVal := mapVal.MapIndex(reflect.ValueOf(key))
	if !elemVal.IsValid() && !reflect.DeepEqual(elemVal.Interface(), elem) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertMapContain failed, map = %v, key = %v, elem = %v, %s", m, key, elem, msg)
		} else {
			t.Fatalf("AssertMapContain failed, map = %v, key = %v, elem = %v", m, key, elem)
		}
	}
}

func AssertMapNotContain(t *testing.T, m, key, elem interface{}, args ...interface{}) {
	mapVal := reflect.ValueOf(m)
	if mapVal.Kind() != reflect.Map {
		panic(fmt.Sprintf("AssertMapNotContain called with non-map value of type %T", m))
	}
	elemVal := mapVal.MapIndex(reflect.ValueOf(key))
	if elemVal.IsValid() && reflect.DeepEqual(elemVal.Interface(), elem) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertMapNotContain failed, map = %v, key = %v, elem = %v, %s", m, key, elem, msg)
		} else {
			t.Fatalf("AssertMapNotContain failed, map = %v, key = %v, elem = %v", m, key, elem)
		}
	}
}

func AssertZero(t *testing.T, val interface{}, args ...interface{}) {
	if !reflect.DeepEqual(reflect.Zero(reflect.TypeOf(val)).Interface(), val) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertZero failed, val = %v, %s", val, msg)
		} else {
			t.Fatalf("AssertZero failed, val = %v", val)
		}
	}
}

func AssertNotZero(t *testing.T, val interface{}, args ...interface{}) {
	if reflect.DeepEqual(reflect.Zero(reflect.TypeOf(val)).Interface(), val) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNotZero failed, val = %v, %s", val, msg)
		} else {
			t.Fatalf("AssertNotZero failed, val = %v", val)
		}
	}
}

func AssertFileExists(t *testing.T, path string, args ...interface{}) {
	if _, err := os.Stat(path); err != nil {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertFileExists failed, path = %v, err = %v, %s", path, err, msg)
		} else {
			t.Fatalf("AssertFileExists failed, path = %v, err = %v", path, err)
		}
	}
}

func AssertFileNotExists(t *testing.T, path string, args ...interface{}) {
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertFileNotExists failed, path = %v, err = %v, %s", path, err, msg)
		} else {
			t.Fatalf("AssertFileNotExists failed, path = %v, err = %v", path, err)
		}
	}
}
<commit_msg>fix argument type<commit_after>// Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package assert provides assert helper functions for testing package.

Example:

	package assert_test

	import (
		"image"
		"math"
		"strings"
		"testing"

		. "github.com/chai2010/assert.go"
	)

	func TestAssert(t *testing.T) {
		Assert(t, 1 == 1)
		Assert(t, 1 == 1, "message1", "message2")
	}

	func TestAssertTrue(t *testing.T) {
		AssertTrue(t, true)
	}

	func TestAssertFalse(t *testing.T) {
		AssertFalse(t, false)
	}

	func TestAssertEqual(t *testing.T) {
		AssertEqual(t, 2, 1+1)
		AssertEqual(t, "abc", strings.ToLower("ABC"))
		AssertEqual(t, image.Pt(1, 2), image.Pt(1, 2))
	}

	func TestAssertNotEqual(t *testing.T) {
		AssertNotEqual(t, 2, 1)
		AssertNotEqual(t, "ABC", strings.ToLower("ABC"))
		AssertNotEqual(t, image.Pt(1, 2), image.Pt(2, 2))
		AssertNotEqual(t, image.Pt(1, 2), image.Rect(1, 2, 3, 4))
	}

	func TestAssertNear(t *testing.T) {
		AssertNear(t, 1.414, math.Sqrt(2), 0.1)
	}

	func TestAssertBetween(t *testing.T) {
		AssertBetween(t, 0, 255, 0)
		AssertBetween(t, 0, 255, 128)
		AssertBetween(t, 0, 255, 255)
	}

	func TestAssertNotBetween(t *testing.T) {
		AssertNotBetween(t, 0, 255, -1)
		AssertNotBetween(t, 0, 255, 256)
	}

	func TestAssertMatch(t *testing.T) {
		AssertMatch(t, `^\w+@\w+\.com$`, "chaishushan@gmail.com")
		AssertMatch(t, `^assert`, "assert.go")
		AssertMatch(t, `\.go$`, "assert.go")
	}

	func TestAssertSliceContain(t *testing.T) {
		AssertSliceContain(t, []int{1, 1, 2, 3, 5, 8, 13}, 8)
		AssertSliceContain(t, []interface{}{1, 1, 2, 3, 5, "8", 13}, "8")
	}

	func TestAssertSliceNotContain(t *testing.T) {
		AssertSliceNotContain(t, []int{1, 1, 2, 3, 5, 8, 13}, 12)
		AssertSliceNotContain(t, []interface{}{1, 1, 2, 3, 5, "8", 13}, 8)
	}

	func TestAssertMapContain(t *testing.T) {
		AssertMapContain(t,
			map[string]int{
				"UTC": 0 * 60 * 60,
				"EST": -5 * 60 * 60,
				"CST": -6 * 60 * 60,
				"MST": -7 * 60 * 60,
				"PST": -8 * 60 * 60,
			},
			"MST", -7*60*60,
		)
	}

	func TestAssertMapNotContain(t *testing.T) {
		AssertMapNotContain(t,
			map[string]int{
				"UTC": 0 * 60 * 60,
				"EST": -5 * 60 * 60,
				"CST": -6 * 60 * 60,
				"MST": -7 * 60 * 60,
				"PST": -8 * 60 * 60,
			},
			"ABC", -7*60*60,
		)
	}

	func TestAssertZero(t *testing.T) {
		AssertZero(t, struct {
			A bool
			B string
			C int
			d map[string]interface{}
		}{})
	}

	func TestAssertNotZero(t *testing.T) {
		AssertNotZero(t, struct {
			A bool
			B string
			C int
			d map[string]interface{}
		}{A: true})
	}

	func TestAssertFileExists(t *testing.T) {
		AssertFileExists(t, "assert.go")
	}

	func TestAssertFileNotExists(t *testing.T) {
		AssertFileNotExists(t, "assert.cc")
	}

Report bugs to <chaishushan@gmail.com>.

Thanks!
*/
package assert

import (
	"fmt"
	"math"
	"os"
	"reflect"
	"regexp"
	"testing"
)

func Assert(t testing.TB, condition bool, args ...interface{}) {
	if !condition {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("Assert failed, %s", msg)
		} else {
			t.Fatal("Assert failed")
		}
	}
}

func AssertTrue(t testing.TB, condition bool, args ...interface{}) {
	if condition != true {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertTrue failed, %s", msg)
		} else {
			t.Fatal("AssertTrue failed")
		}
	}
}

func AssertFalse(t testing.TB, condition bool, args ...interface{}) {
	if condition != false {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertFalse failed, %s", msg)
		} else {
			t.Fatal("AssertFalse failed")
		}
	}
}

func AssertEqual(t testing.TB, expected, got interface{}, args ...interface{}) {
	if !reflect.DeepEqual(expected, got) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertEqual failed, expected = %v, got = %v, %s", expected, got, msg)
		} else {
			t.Fatalf("AssertEqual failed, expected = %v, got = %v", expected, got)
		}
	}
}

func AssertNotEqual(t testing.TB, expected, got interface{}, args ...interface{}) {
	if reflect.DeepEqual(expected, got) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNotEqual failed, expected = %v, got = %v, %s", expected, got, msg)
		} else {
			t.Fatalf("AssertNotEqual failed, expected = %v, got = %v", expected, got)
		}
	}
}

func AssertNear(t testing.TB, expected, got, abs float64, args ...interface{}) {
	if math.Abs(expected-got) > abs {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNear failed, expected = %v, got = %v, abs = %v, %s", expected, got, abs, msg)
		} else {
			t.Fatalf("AssertNear failed, expected = %v, got = %v, abs = %v", expected, got, abs)
		}
	}
}

func AssertBetween(t testing.TB, min, max, val float64, args ...interface{}) {
	if val < min || max < val {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertBetween failed, min = %v, max = %v, val = %v, %s", min, max, val, msg)
		} else {
			t.Fatalf("AssertBetween failed, min = %v, max = %v, val = %v", min, max, val)
		}
	}
}

func AssertNotBetween(t testing.TB, min, max, val float64, args ...interface{}) {
	if min <= val && val <= max {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNotBetween failed, min = %v, max = %v, val = %v, %s", min, max, val, msg)
		} else {
			t.Fatalf("AssertNotBetween failed, min = %v, max = %v, val = %v", min, max, val)
		}
	}
}

func AssertMatch(t testing.TB, expectedPattern, got string, args ...interface{}) {
	if matched, err := regexp.MatchString(expectedPattern, got); err != nil || !matched {
		if err != nil {
			if msg := fmt.Sprint(args...); msg != "" {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v, err = %v, %s", expectedPattern, got, err, msg)
			} else {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v, err = %v", expectedPattern, got, err)
			}
		} else {
			if msg := fmt.Sprint(args...); msg != "" {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v, %s", expectedPattern, got, msg)
			} else {
				t.Fatalf("AssertMatch failed, expected = %q, got = %v", expectedPattern, got)
			}
		}
	}
}

func AssertSliceContain(t testing.TB, slice, elem interface{}, args ...interface{}) {
	sliceVal := reflect.ValueOf(slice)
	if sliceVal.Kind() != reflect.Slice {
		panic(fmt.Sprintf("AssertSliceContain called with non-slice value of type %T", slice))
	}
	var contained bool
	for i := 0; i < sliceVal.Len(); i++ {
		if reflect.DeepEqual(sliceVal.Index(i).Interface(), elem) {
			contained = true
			break
		}
	}
	if !contained {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertSliceContain failed, slice = %v, elem = %v, %s", slice, elem, msg)
		} else {
			t.Fatalf("AssertSliceContain failed, slice = %v, elem = %v", slice, elem)
		}
	}
}

func AssertSliceNotContain(t testing.TB, slice, elem interface{}, args ...interface{}) {
	sliceVal := reflect.ValueOf(slice)
	if sliceVal.Kind() != reflect.Slice {
		panic(fmt.Sprintf("AssertSliceNotContain called with non-slice value of type %T", slice))
	}
	var contained bool
	for i := 0; i < sliceVal.Len(); i++ {
		if reflect.DeepEqual(sliceVal.Index(i).Interface(), elem) {
			contained = true
			break
		}
	}
	if contained {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertSliceNotContain failed, slice = %v, elem = %v, %s", slice, elem, msg)
		} else {
			t.Fatalf("AssertSliceNotContain failed, slice = %v, elem = %v", slice, elem)
		}
	}
}

func AssertMapContain(t testing.TB, m, key, elem interface{}, args ...interface{}) {
	mapVal := reflect.ValueOf(m)
	if mapVal.Kind() != reflect.Map {
		panic(fmt.Sprintf("AssertMapContain called with non-map value of type %T", m))
	}
	elemVal := mapVal.MapIndex(reflect.ValueOf(key))
	if !elemVal.IsValid() && !reflect.DeepEqual(elemVal.Interface(), elem) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertMapContain failed, map = %v, key = %v, elem = %v, %s", m, key, elem, msg)
		} else {
			t.Fatalf("AssertMapContain failed, map = %v, key = %v, elem = %v", m, key, elem)
		}
	}
}

func AssertMapNotContain(t testing.TB, m, key, elem interface{}, args ...interface{}) {
	mapVal := reflect.ValueOf(m)
	if mapVal.Kind() != reflect.Map {
		panic(fmt.Sprintf("AssertMapNotContain called with non-map value of type %T", m))
	}
	elemVal := mapVal.MapIndex(reflect.ValueOf(key))
	if elemVal.IsValid() && reflect.DeepEqual(elemVal.Interface(), elem) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertMapNotContain failed, map = %v, key = %v, elem = %v, %s", m, key, elem, msg)
		} else {
			t.Fatalf("AssertMapNotContain failed, map = %v, key = %v, elem = %v", m, key, elem)
		}
	}
}

func AssertZero(t testing.TB, val interface{}, args ...interface{}) {
	if !reflect.DeepEqual(reflect.Zero(reflect.TypeOf(val)).Interface(), val) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertZero failed, val = %v, %s", val, msg)
		} else {
			t.Fatalf("AssertZero failed, val = %v", val)
		}
	}
}

func AssertNotZero(t testing.TB, val interface{}, args ...interface{}) {
	if reflect.DeepEqual(reflect.Zero(reflect.TypeOf(val)).Interface(), val) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertNotZero failed, val = %v, %s", val, msg)
		} else {
			t.Fatalf("AssertNotZero failed, val = %v", val)
		}
	}
}

func AssertFileExists(t testing.TB, path string, args ...interface{}) {
	if _, err := os.Stat(path); err != nil {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertFileExists failed, path = %v, err = %v, %s", path, err, msg)
		} else {
			t.Fatalf("AssertFileExists failed, path = %v, err = %v", path, err)
		}
	}
}

func AssertFileNotExists(t testing.TB, path string, args ...interface{}) {
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		if msg := fmt.Sprint(args...); msg != "" {
			t.Fatalf("AssertFileNotExists failed, path = %v, err = %v, %s", path, err, msg)
		} else {
			t.Fatalf("AssertFileNotExists failed, path = %v, err = %v", path, err)
		}
	}
}
<|endoftext|>


<commit_before>package colonycore

import (
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
)

type WebGrabber struct {
	orm.ModelBase
	ID                string `json:"_id",bson:"_id"`
	CallType          string
	SourceType        string
	IntervalType      string
	GrabInterval      int32
	TimeoutInterval   int32
	URL               string
	LogConfiguration  *LogConfiguration
	DataSettings      []*DataSetting
	GrabConfiguration *GrabConfiguration
	Parameter         []*Parameter
}

func (ds *WebGrabber) TableName() string {
	return "webgrabber"
}

func (ds *WebGrabber) RecordID() interface{} {
	return ds.ID
}

type LogConfiguration struct {
	FileName    string
	FilePattern string
	LogPath     string
}

type DataSetting struct {
	ColumnSettings     []*ColumnSetting
	ConnectionInfo     *ConnectionInfo
	DestinationType    string
	Name               string
	RowDeleteCondition toolkit.M
	RowSelector        string
}

type ConnectionInfo struct {
	Collection string
	Database   string
	Host       string
}

type ColumnSetting struct {
	Alias    string
	Index    int
	Selector string
}

type GrabConfiguration struct {
	Data toolkit.M
}

type Parameter struct {
	Format  string
	Key     string
	Pattern string
	Value   interface{}
}
<commit_msg>no message<commit_after>package colonycore

import (
	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
)

type WebGrabber struct {
	orm.ModelBase
	ID                string `json:"_id",bson:"_id"`
	CallType          string
	SourceType        string
	IntervalType      string
	GrabInterval      int32
	TimeoutInterval   int32
	URL               string
	LogConfiguration  *LogConfiguration
	DataSettings      []*DataSetting
	GrabConfiguration toolkit.M
	Parameter         []*Parameter
}

func (ds *WebGrabber) TableName() string {
	return "webgrabbers"
}

func (ds *WebGrabber) RecordID() interface{} {
	return ds.ID
}

type LogConfiguration struct {
	FileName    string
	FilePattern string
	LogPath     string
}

type ConnectionInfo struct {
	dbox.ConnectionInfo
	Collection string
}

type DataSetting struct {
	RowSelector     string
	FilterCondition toolkit.M
	ColumnSettings  []*ColumnSetting

	RowDeleteCondition  toolkit.M
	RowIncludeCondition toolkit.M

	ConnectionInfo  *ConnectionInfo
	DestinationType string
	Name            string
}

func (ds *DataSetting) Column(i int, column *ColumnSetting) *ColumnSetting {
	if i == 0 {
		ds.ColumnSettings = append(ds.ColumnSettings, column)
	} else if i <= len(ds.ColumnSettings) {
		ds.ColumnSettings[i-1] = column
	} else {
		return nil
	}
	return column
}

type ColumnSetting struct {
	Alias     string
	Index     int
	Selector  string
	ValueType string
}

type Parameter struct {
	Format  string
	Key     string
	Pattern string
	Value   interface{}
}
<|endoftext|>


<commit_before>/*
Copyright 2016 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 rest

import (
	"fmt"

	"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/test_apis/testgroup"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/fields"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/registry/generic"
	"k8s.io/kubernetes/pkg/registry/generic/registry"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/storage"
	"k8s.io/kubernetes/pkg/storage/storagebackend"
)

type REST struct {
	*registry.Store
}

// NewREST returns a RESTStorage object that will work with testtype.
func NewREST(config *storagebackend.Config, storageDecorator generic.StorageDecorator) *REST {
	prefix := "/testtype"
	newListFunc := func() runtime.Object { return &testgroup.TestTypeList{} }
	// Usually you should reuse your RESTCreateStrategy.
	strategy := &NotNamespaceScoped{}
	storageInterface, _ := storageDecorator(
		config, 100, &testgroup.TestType{}, prefix, strategy, newListFunc, storage.NoTriggerPublisher)
	store := &registry.Store{
		NewFunc: func() runtime.Object { return &testgroup.TestType{} },
		// NewListFunc returns an object capable of storing results of an etcd list.
		NewListFunc: newListFunc,
		// Produces a path that etcd understands, to the root of the resource
		// by combining the namespace in the context with the given prefix.
		KeyRootFunc: func(ctx api.Context) string {
			return registry.NamespaceKeyRootFunc(ctx, prefix)
		},
		// Produces a path that etcd understands, to the resource by combining
		// the namespace in the context with the given prefix.
		KeyFunc: func(ctx api.Context, name string) (string, error) {
			return registry.NamespaceKeyFunc(ctx, prefix, name)
		},
		// Retrieve the name field of the resource.
		ObjectNameFunc: func(obj runtime.Object) (string, error) {
			return obj.(*testgroup.TestType).Name, nil
		},
		// Used to match objects based on labels/fields for list.
		PredicateFunc: func(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
			return storage.SelectionPredicate{
				Label: label,
				Field: field,
				GetAttrs: func(obj runtime.Object) (labels.Set, fields.Set, error) {
					testType, ok := obj.(*testgroup.TestType)
					if !ok {
						return nil, nil, fmt.Errorf("unexpected type of given object")
					}
					return labels.Set(testType.ObjectMeta.Labels), fields.Set{}, nil
				},
			}
		},
		Storage: storageInterface,
	}
	return &REST{store}
}

type NotNamespaceScoped struct {
}

func (*NotNamespaceScoped) NamespaceScoped() bool {
	return false
}
<commit_msg>Cache fields for filtering in watchCache.<commit_after>/*
Copyright 2016 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 rest

import (
	"fmt"

	"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/test_apis/testgroup"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/fields"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/registry/generic"
	"k8s.io/kubernetes/pkg/registry/generic/registry"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/storage"
	"k8s.io/kubernetes/pkg/storage/storagebackend"
)

type REST struct {
	*registry.Store
}

// NewREST returns a RESTStorage object that will work with testtype.
func NewREST(config *storagebackend.Config, storageDecorator generic.StorageDecorator) *REST {
	prefix := "/testtype"
	newListFunc := func() runtime.Object { return &testgroup.TestTypeList{} }
	// Usually you should reuse your RESTCreateStrategy.
	strategy := &NotNamespaceScoped{}
	getAttrs := func(obj runtime.Object) (labels.Set, fields.Set, error) {
		testObj, ok := obj.(*testgroup.TestType)
		if !ok {
			return nil, nil, fmt.Errorf("not a TestType")
		}
		return labels.Set(testObj.Labels), nil, nil
	}
	storageInterface, _ := storageDecorator(
		config, 100, &testgroup.TestType{}, prefix, strategy, newListFunc, getAttrs, storage.NoTriggerPublisher)
	store := &registry.Store{
		NewFunc: func() runtime.Object { return &testgroup.TestType{} },
		// NewListFunc returns an object capable of storing results of an etcd list.
		NewListFunc: newListFunc,
		// Produces a path that etcd understands, to the root of the resource
		// by combining the namespace in the context with the given prefix.
		KeyRootFunc: func(ctx api.Context) string {
			return registry.NamespaceKeyRootFunc(ctx, prefix)
		},
		// Produces a path that etcd understands, to the resource by combining
		// the namespace in the context with the given prefix.
		KeyFunc: func(ctx api.Context, name string) (string, error) {
			return registry.NamespaceKeyFunc(ctx, prefix, name)
		},
		// Retrieve the name field of the resource.
		ObjectNameFunc: func(obj runtime.Object) (string, error) {
			return obj.(*testgroup.TestType).Name, nil
		},
		// Used to match objects based on labels/fields for list.
		PredicateFunc: func(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
			return storage.SelectionPredicate{
				Label: label,
				Field: field,
				GetAttrs: func(obj runtime.Object) (labels.Set, fields.Set, error) {
					testType, ok := obj.(*testgroup.TestType)
					if !ok {
						return nil, nil, fmt.Errorf("unexpected type of given object")
					}
					return labels.Set(testType.ObjectMeta.Labels), fields.Set{}, nil
				},
			}
		},
		Storage: storageInterface,
	}
	return &REST{store}
}

type NotNamespaceScoped struct {
}

func (*NotNamespaceScoped) NamespaceScoped() bool {
	return false
}
<|endoftext|>


<commit_before>package test

import (
	"io/ioutil"
	"log"
	"net/http"
	"testing"
)

func TestHealthReload(t *testing.T) {
	log.SetOutput(ioutil.Discard)

	// Corefile with for example without proxy section.
	corefile := `example.org:0 {
	health localhost:35080
}
`
	i, err := CoreDNSServer(corefile)
	if err != nil {
		t.Fatalf("Could not get CoreDNS serving instance: %s", err)
	}

	resp, err := http.Get("http://localhost:35080/health")
	if err != nil {
		t.Fatalf("Could not get health: %s", err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if x := string(body); x != "OK" {
		t.Fatalf("Expect OK, got %s", x)
	}
	resp.Body.Close()

	i, err = i.Restart(NewInput(corefile))
	if err != nil {
		t.Fatalf("Could not restart CoreDNS serving instance: %s", err)
	}

	defer i.Stop()

	resp, err = http.Get("http://localhost:35080/health")
	if err != nil {
		t.Fatalf("Could not get health: %s", err)
	}
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Could not get resp.Body: %s", err)
	}
	if x := string(body); x != "OK" {
		t.Fatalf("Expect OK, got %s", x)
	}
	resp.Body.Close()
}
<commit_msg>test: remove health reload test (#1142)<commit_after><|endoftext|>


<commit_before>package logmon

import (
	"crypto/rand"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/hashicorp/nomad/client/lib/fifo"
	"github.com/hashicorp/nomad/helper/testlog"
	"github.com/hashicorp/nomad/testutil"
	"github.com/stretchr/testify/require"
)

func TestLogmon_Start_rotate(t *testing.T) {
	require := require.New(t)

	stdoutLog := "stdout"
	stderrLog := "stderr"

	var stdoutFifoPath, stderrFifoPath string

	dir, err := ioutil.TempDir("", "nomadtest")
	require.NoError(err)
	defer os.RemoveAll(dir)

	if runtime.GOOS == "windows" {
		stdoutFifoPath = "//./pipe/test-rotate.stdout"
		stderrFifoPath = "//./pipe/test-rotate.stderr"
	} else {
		stdoutFifoPath = filepath.Join(dir, "stdout.fifo")
		stderrFifoPath = filepath.Join(dir, "stderr.fifo")
	}

	cfg := &LogConfig{
		LogDir:        dir,
		StdoutLogFile: stdoutLog,
		StdoutFifo:    stdoutFifoPath,
		StderrLogFile: stderrLog,
		StderrFifo:    stderrFifoPath,
		MaxFiles:      2,
		MaxFileSizeMB: 1,
	}

	lm := NewLogMon(testlog.HCLogger(t))
	require.NoError(lm.Start(cfg))

	stdout, err := fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)

	// Write enough bytes such that the log is rotated
	bytes1MB := make([]byte, 1024*1024)
	_, err = rand.Read(bytes1MB)
	require.NoError(err)

	_, err = stdout.Write(bytes1MB)
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		_, err = os.Stat(filepath.Join(dir, "stdout.0"))
		return err == nil, err
	}, func(err error) {
		require.NoError(err)
	})
	testutil.WaitForResult(func() (bool, error) {
		_, err = os.Stat(filepath.Join(dir, "stdout.1"))
		return err == nil, err
	}, func(err error) {
		require.NoError(err)
	})
	_, err = os.Stat(filepath.Join(dir, "stdout.2"))
	require.Error(err)
	require.NoError(lm.Stop())
	require.NoError(lm.Stop())
}

// asserts that calling Start twice restarts the log rotator
func TestLogmon_Start_restart(t *testing.T) {
	require := require.New(t)

	stdoutLog := "stdout"
	stderrLog := "stderr"

	var stdoutFifoPath, stderrFifoPath string

	dir, err := ioutil.TempDir("", "nomadtest")
	require.NoError(err)
	defer os.RemoveAll(dir)

	if runtime.GOOS == "windows" {
		stdoutFifoPath = "//./pipe/test-restart.stdout"
		stderrFifoPath = "//./pipe/test-restart.stderr"
	} else {
		stdoutFifoPath = filepath.Join(dir, "stdout.fifo")
		stderrFifoPath = filepath.Join(dir, "stderr.fifo")
	}

	cfg := &LogConfig{
		LogDir:        dir,
		StdoutLogFile: stdoutLog,
		StdoutFifo:    stdoutFifoPath,
		StderrLogFile: stderrLog,
		StderrFifo:    stderrFifoPath,
		MaxFiles:      2,
		MaxFileSizeMB: 1,
	}

	lm := NewLogMon(testlog.HCLogger(t))
	impl, ok := lm.(*logmonImpl)
	require.True(ok)
	require.NoError(lm.Start(cfg))

	stdout, err := fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)
	stderr, err := fifo.OpenWriter(stderrFifoPath)
	require.NoError(err)

	// Write a string and assert it was written to the file
	_, err = stdout.Write([]byte("test\n"))
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}
		return "test\n" == string(raw), fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})
	require.True(impl.tl.IsRunning())

	// Close stdout and assert that logmon no longer writes to the file
	require.NoError(stdout.Close())
	require.NoError(stderr.Close())

	testutil.WaitForResult(func() (bool, error) {
		return !impl.tl.IsRunning(), fmt.Errorf("logmon is still running")
	}, func(err error) {
		require.NoError(err)
	})

	require.NoError(lm.Stop())

	// Start logmon again and assert that it appended to the file
	require.NoError(lm.Start(cfg))

	stdout, err = fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)
	stderr, err = fifo.OpenWriter(stderrFifoPath)
	require.NoError(err)

	_, err = stdout.Write([]byte("te"))
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}
		return "test\n" == string(raw), fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})

	_, err = stdout.Write([]byte("st\n"))
	require.NoError(err)
	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}

		expected := "test\ntest\n" == string(raw)
		return expected, fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})
}
<commit_msg>logmon: Add windows compatibility test<commit_after>package logmon

import (
	"crypto/rand"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/hashicorp/nomad/client/lib/fifo"
	"github.com/hashicorp/nomad/helper/testlog"
	"github.com/hashicorp/nomad/testutil"
	"github.com/stretchr/testify/require"
)

func TestLogmon_Start_rotate(t *testing.T) {
	require := require.New(t)

	stdoutLog := "stdout"
	stderrLog := "stderr"

	var stdoutFifoPath, stderrFifoPath string

	dir, err := ioutil.TempDir("", "nomadtest")
	require.NoError(err)
	defer os.RemoveAll(dir)

	if runtime.GOOS == "windows" {
		stdoutFifoPath = "//./pipe/test-rotate.stdout"
		stderrFifoPath = "//./pipe/test-rotate.stderr"
	} else {
		stdoutFifoPath = filepath.Join(dir, "stdout.fifo")
		stderrFifoPath = filepath.Join(dir, "stderr.fifo")
	}

	cfg := &LogConfig{
		LogDir:        dir,
		StdoutLogFile: stdoutLog,
		StdoutFifo:    stdoutFifoPath,
		StderrLogFile: stderrLog,
		StderrFifo:    stderrFifoPath,
		MaxFiles:      2,
		MaxFileSizeMB: 1,
	}

	lm := NewLogMon(testlog.HCLogger(t))
	require.NoError(lm.Start(cfg))

	stdout, err := fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)

	// Write enough bytes such that the log is rotated
	bytes1MB := make([]byte, 1024*1024)
	_, err = rand.Read(bytes1MB)
	require.NoError(err)

	_, err = stdout.Write(bytes1MB)
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		_, err = os.Stat(filepath.Join(dir, "stdout.0"))
		return err == nil, err
	}, func(err error) {
		require.NoError(err)
	})
	testutil.WaitForResult(func() (bool, error) {
		_, err = os.Stat(filepath.Join(dir, "stdout.1"))
		return err == nil, err
	}, func(err error) {
		require.NoError(err)
	})
	_, err = os.Stat(filepath.Join(dir, "stdout.2"))
	require.Error(err)
	require.NoError(lm.Stop())
	require.NoError(lm.Stop())
}

// asserts that calling Start twice restarts the log rotator and that any logs
// published while the listener was unavailable are recieved.
func TestLogmon_Start_restart_flusheslogs(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("windows does not support pushing data to a pipe with no servers")
	}

	require := require.New(t)

	stdoutLog := "stdout"
	stderrLog := "stderr"

	var stdoutFifoPath, stderrFifoPath string

	dir, err := ioutil.TempDir("", "nomadtest")
	require.NoError(err)
	defer os.RemoveAll(dir)

	if runtime.GOOS == "windows" {
		stdoutFifoPath = "//./pipe/test-restart.stdout"
		stderrFifoPath = "//./pipe/test-restart.stderr"
	} else {
		stdoutFifoPath = filepath.Join(dir, "stdout.fifo")
		stderrFifoPath = filepath.Join(dir, "stderr.fifo")
	}

	cfg := &LogConfig{
		LogDir:        dir,
		StdoutLogFile: stdoutLog,
		StdoutFifo:    stdoutFifoPath,
		StderrLogFile: stderrLog,
		StderrFifo:    stderrFifoPath,
		MaxFiles:      2,
		MaxFileSizeMB: 1,
	}

	lm := NewLogMon(testlog.HCLogger(t))
	impl, ok := lm.(*logmonImpl)
	require.True(ok)
	require.NoError(lm.Start(cfg))

	stdout, err := fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)
	stderr, err := fifo.OpenWriter(stderrFifoPath)
	require.NoError(err)

	// Write a string and assert it was written to the file
	_, err = stdout.Write([]byte("test\n"))
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}
		return "test\n" == string(raw), fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})
	require.True(impl.tl.IsRunning())

	// Close stdout and assert that logmon no longer writes to the file
	require.NoError(stdout.Close())
	require.NoError(stderr.Close())

	testutil.WaitForResult(func() (bool, error) {
		return !impl.tl.IsRunning(), fmt.Errorf("logmon is still running")
	}, func(err error) {
		require.NoError(err)
	})

	require.NoError(lm.Stop())

	// Start logmon again and assert that it appended to the file
	require.NoError(lm.Start(cfg))

	stdout, err = fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)
	stderr, err = fifo.OpenWriter(stderrFifoPath)
	require.NoError(err)

	_, err = stdout.Write([]byte("te"))
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}
		return "test\n" == string(raw), fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})

	_, err = stdout.Write([]byte("st\n"))
	require.NoError(err)
	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}

		expected := "test\ntest\n" == string(raw)
		return expected, fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})
}

// asserts that calling Start twice restarts the log rotator
func TestLogmon_Start_restart(t *testing.T) {
	require := require.New(t)

	stdoutLog := "stdout"
	stderrLog := "stderr"

	var stdoutFifoPath, stderrFifoPath string

	dir, err := ioutil.TempDir("", "nomadtest")
	require.NoError(err)
	defer os.RemoveAll(dir)

	if runtime.GOOS == "windows" {
		stdoutFifoPath = "//./pipe/test-restart.stdout"
		stderrFifoPath = "//./pipe/test-restart.stderr"
	} else {
		stdoutFifoPath = filepath.Join(dir, "stdout.fifo")
		stderrFifoPath = filepath.Join(dir, "stderr.fifo")
	}

	cfg := &LogConfig{
		LogDir:        dir,
		StdoutLogFile: stdoutLog,
		StdoutFifo:    stdoutFifoPath,
		StderrLogFile: stderrLog,
		StderrFifo:    stderrFifoPath,
		MaxFiles:      2,
		MaxFileSizeMB: 1,
	}

	lm := NewLogMon(testlog.HCLogger(t))
	impl, ok := lm.(*logmonImpl)
	require.True(ok)
	require.NoError(lm.Start(cfg))

	stdout, err := fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)
	stderr, err := fifo.OpenWriter(stderrFifoPath)
	require.NoError(err)

	// Write a string and assert it was written to the file
	_, err = stdout.Write([]byte("test\n"))
	require.NoError(err)

	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}
		return "test\n" == string(raw), fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})
	require.True(impl.tl.IsRunning())

	// Close stdout and assert that logmon no longer writes to the file
	require.NoError(stdout.Close())
	require.NoError(stderr.Close())

	testutil.WaitForResult(func() (bool, error) {
		return !impl.tl.IsRunning(), fmt.Errorf("logmon is still running")
	}, func(err error) {
		require.NoError(err)
	})

	// Start logmon again and assert that it can recieve logs again
	require.NoError(lm.Start(cfg))

	stdout, err = fifo.OpenWriter(stdoutFifoPath)
	require.NoError(err)
	stderr, err = fifo.OpenWriter(stderrFifoPath)
	require.NoError(err)

	_, err = stdout.Write([]byte("test\n"))
	require.NoError(err)
	testutil.WaitForResult(func() (bool, error) {
		raw, err := ioutil.ReadFile(filepath.Join(dir, "stdout.0"))
		if err != nil {
			return false, err
		}

		expected := "test\ntest\n" == string(raw)
		return expected, fmt.Errorf("unexpected stdout %q", string(raw))
	}, func(err error) {
		require.NoError(err)
	})
}
<|endoftext|>