From 9b12e4fe6f3c95986f1f3ec791636c58ca7e7583 Mon Sep 17 00:00:00 2001 From: Jake Champlin Date: Fri, 9 Jun 2017 17:54:32 +0000 Subject: Transfer of provider code --- .../hashicorp/terraform/helper/acctest/acctest.go | 2 - .../hashicorp/terraform/helper/acctest/random.go | 93 ------------- .../terraform/helper/acctest/remotetests.go | 27 ---- .../hashicorp/terraform/helper/resource/testing.go | 148 +++++++++++++++++++++ .../terraform/helper/schema/provisioner.go | 30 ++++- .../hashicorp/terraform/helper/schema/schema.go | 4 +- .../terraform/helper/structure/expand_json.go | 11 -- .../terraform/helper/structure/flatten_json.go | 16 --- .../terraform/helper/structure/normalize_json.go | 24 ---- .../helper/structure/suppress_json_diff.go | 21 --- .../terraform/helper/validation/validation.go | 108 --------------- 11 files changed, 178 insertions(+), 306 deletions(-) delete mode 100644 vendor/github.com/hashicorp/terraform/helper/acctest/acctest.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/acctest/random.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/acctest/remotetests.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/structure/expand_json.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/structure/flatten_json.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/structure/normalize_json.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/structure/suppress_json_diff.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/validation/validation.go (limited to 'vendor/github.com/hashicorp/terraform/helper') diff --git a/vendor/github.com/hashicorp/terraform/helper/acctest/acctest.go b/vendor/github.com/hashicorp/terraform/helper/acctest/acctest.go deleted file mode 100644 index 9d31031..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/acctest/acctest.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package acctest contains for Terraform Acceptance Tests -package acctest diff --git a/vendor/github.com/hashicorp/terraform/helper/acctest/random.go b/vendor/github.com/hashicorp/terraform/helper/acctest/random.go deleted file mode 100644 index 3ddc078..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/acctest/random.go +++ /dev/null @@ -1,93 +0,0 @@ -package acctest - -import ( - "bufio" - "bytes" - crand "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "fmt" - "math/rand" - "strings" - "time" - - "golang.org/x/crypto/ssh" -) - -// Helpers for generating random tidbits for use in identifiers to prevent -// collisions in acceptance tests. - -// RandInt generates a random integer -func RandInt() int { - reseed() - return rand.New(rand.NewSource(time.Now().UnixNano())).Int() -} - -// RandomWithPrefix is used to generate a unique name with a prefix, for -// randomizing names in acceptance tests -func RandomWithPrefix(name string) string { - reseed() - return fmt.Sprintf("%s-%d", name, rand.New(rand.NewSource(time.Now().UnixNano())).Int()) -} - -func RandIntRange(min int, max int) int { - reseed() - source := rand.New(rand.NewSource(time.Now().UnixNano())) - rangeMax := max - min - - return int(source.Int31n(int32(rangeMax))) -} - -// RandString generates a random alphanumeric string of the length specified -func RandString(strlen int) string { - return RandStringFromCharSet(strlen, CharSetAlphaNum) -} - -// RandStringFromCharSet generates a random string by selecting characters from -// the charset provided -func RandStringFromCharSet(strlen int, charSet string) string { - reseed() - result := make([]byte, strlen) - for i := 0; i < strlen; i++ { - result[i] = charSet[rand.Intn(len(charSet))] - } - return string(result) -} - -// RandSSHKeyPair generates a public and private SSH key pair. The public key is -// returned in OpenSSH format, and the private key is PEM encoded. -func RandSSHKeyPair(comment string) (string, string, error) { - privateKey, err := rsa.GenerateKey(crand.Reader, 1024) - if err != nil { - return "", "", err - } - - var privateKeyBuffer bytes.Buffer - privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} - if err := pem.Encode(bufio.NewWriter(&privateKeyBuffer), privateKeyPEM); err != nil { - return "", "", err - } - - publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey) - if err != nil { - return "", "", err - } - keyMaterial := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(publicKey))) - return fmt.Sprintf("%s %s", keyMaterial, comment), privateKeyBuffer.String(), nil -} - -// Seeds random with current timestamp -func reseed() { - rand.Seed(time.Now().UTC().UnixNano()) -} - -const ( - // CharSetAlphaNum is the alphanumeric character set for use with - // RandStringFromCharSet - CharSetAlphaNum = "abcdefghijklmnopqrstuvwxyz012346789" - - // CharSetAlpha is the alphabetical character set for use with - // RandStringFromCharSet - CharSetAlpha = "abcdefghijklmnopqrstuvwxyz" -) diff --git a/vendor/github.com/hashicorp/terraform/helper/acctest/remotetests.go b/vendor/github.com/hashicorp/terraform/helper/acctest/remotetests.go deleted file mode 100644 index 87c60b8..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/acctest/remotetests.go +++ /dev/null @@ -1,27 +0,0 @@ -package acctest - -import ( - "net/http" - "os" - "testing" -) - -// SkipRemoteTestsEnvVar is an environment variable that can be set by a user -// running the tests in an environment with limited network connectivity. By -// default, tests requiring internet connectivity make an effort to skip if no -// internet is available, but in some cases the smoke test will pass even -// though the test should still be skipped. -const SkipRemoteTestsEnvVar = "TF_SKIP_REMOTE_TESTS" - -// RemoteTestPrecheck is meant to be run by any unit test that requires -// outbound internet connectivity. The test will be skipped if it's -// unavailable. -func RemoteTestPrecheck(t *testing.T) { - if os.Getenv(SkipRemoteTestsEnvVar) != "" { - t.Skipf("skipping test, %s was set", SkipRemoteTestsEnvVar) - } - - if _, err := http.Get("http://google.com"); err != nil { - t.Skipf("skipping, internet seems to not be available: %s", err) - } -} diff --git a/vendor/github.com/hashicorp/terraform/helper/resource/testing.go b/vendor/github.com/hashicorp/terraform/helper/resource/testing.go index 04367c5..ebdbde2 100644 --- a/vendor/github.com/hashicorp/terraform/helper/resource/testing.go +++ b/vendor/github.com/hashicorp/terraform/helper/resource/testing.go @@ -1,6 +1,7 @@ package resource import ( + "flag" "fmt" "io" "io/ioutil" @@ -20,6 +21,153 @@ import ( "github.com/hashicorp/terraform/terraform" ) +// flagSweep is a flag available when running tests on the command line. It +// contains a comma seperated list of regions to for the sweeper functions to +// run in. This flag bypasses the normal Test path and instead runs functions designed to +// clean up any leaked resources a testing environment could have created. It is +// a best effort attempt, and relies on Provider authors to implement "Sweeper" +// methods for resources. + +// Adding Sweeper methods with AddTestSweepers will +// construct a list of sweeper funcs to be called here. We iterate through +// regions provided by the sweep flag, and for each region we iterate through the +// tests, and exit on any errors. At time of writing, sweepers are ran +// sequentially, however they can list dependencies to be ran first. We track +// the sweepers that have been ran, so as to not run a sweeper twice for a given +// region. +// +// WARNING: +// Sweepers are designed to be destructive. You should not use the -sweep flag +// in any environment that is not strictly a test environment. Resources will be +// destroyed. + +var flagSweep = flag.String("sweep", "", "List of Regions to run available Sweepers") +var flagSweepRun = flag.String("sweep-run", "", "Comma seperated list of Sweeper Tests to run") +var sweeperFuncs map[string]*Sweeper + +// map of sweepers that have ran, and the success/fail status based on any error +// raised +var sweeperRunList map[string]bool + +// type SweeperFunc is a signature for a function that acts as a sweeper. It +// accepts a string for the region that the sweeper is to be ran in. This +// function must be able to construct a valid client for that region. +type SweeperFunc func(r string) error + +type Sweeper struct { + // Name for sweeper. Must be unique to be ran by the Sweeper Runner + Name string + + // Dependencies list the const names of other Sweeper functions that must be ran + // prior to running this Sweeper. This is an ordered list that will be invoked + // recursively at the helper/resource level + Dependencies []string + + // Sweeper function that when invoked sweeps the Provider of specific + // resources + F SweeperFunc +} + +func init() { + sweeperFuncs = make(map[string]*Sweeper) +} + +// AddTestSweepers function adds a given name and Sweeper configuration +// pair to the internal sweeperFuncs map. Invoke this function to register a +// resource sweeper to be available for running when the -sweep flag is used +// with `go test`. Sweeper names must be unique to help ensure a given sweeper +// is only ran once per run. +func AddTestSweepers(name string, s *Sweeper) { + if _, ok := sweeperFuncs[name]; ok { + log.Fatalf("[ERR] Error adding (%s) to sweeperFuncs: function already exists in map", name) + } + + sweeperFuncs[name] = s +} + +func TestMain(m *testing.M) { + flag.Parse() + if *flagSweep != "" { + // parse flagSweep contents for regions to run + regions := strings.Split(*flagSweep, ",") + + // get filtered list of sweepers to run based on sweep-run flag + sweepers := filterSweepers(*flagSweepRun, sweeperFuncs) + for _, region := range regions { + region = strings.TrimSpace(region) + // reset sweeperRunList for each region + sweeperRunList = map[string]bool{} + + log.Printf("[DEBUG] Running Sweepers for region (%s):\n", region) + for _, sweeper := range sweepers { + if err := runSweeperWithRegion(region, sweeper); err != nil { + log.Fatalf("[ERR] error running (%s): %s", sweeper.Name, err) + } + } + + log.Printf("Sweeper Tests ran:\n") + for s, _ := range sweeperRunList { + fmt.Printf("\t- %s\n", s) + } + } + } else { + os.Exit(m.Run()) + } +} + +// filterSweepers takes a comma seperated string listing the names of sweepers +// to be ran, and returns a filtered set from the list of all of sweepers to +// run based on the names given. +func filterSweepers(f string, source map[string]*Sweeper) map[string]*Sweeper { + filterSlice := strings.Split(strings.ToLower(f), ",") + if len(filterSlice) == 1 && filterSlice[0] == "" { + // if the filter slice is a single element of "" then no sweeper list was + // given, so just return the full list + return source + } + + sweepers := make(map[string]*Sweeper) + for name, sweeper := range source { + for _, s := range filterSlice { + if strings.Contains(strings.ToLower(name), s) { + sweepers[name] = sweeper + } + } + } + return sweepers +} + +// runSweeperWithRegion recieves a sweeper and a region, and recursively calls +// itself with that region for every dependency found for that sweeper. If there +// are no dependencies, invoke the contained sweeper fun with the region, and +// add the success/fail status to the sweeperRunList. +func runSweeperWithRegion(region string, s *Sweeper) error { + for _, dep := range s.Dependencies { + if depSweeper, ok := sweeperFuncs[dep]; ok { + log.Printf("[DEBUG] Sweeper (%s) has dependency (%s), running..", s.Name, dep) + if err := runSweeperWithRegion(region, depSweeper); err != nil { + return err + } + } else { + log.Printf("[DEBUG] Sweeper (%s) has dependency (%s), but that sweeper was not found", s.Name, dep) + } + } + + if _, ok := sweeperRunList[s.Name]; ok { + log.Printf("[DEBUG] Sweeper (%s) already ran in region (%s)", s.Name, region) + return nil + } + + runE := s.F(region) + if runE == nil { + sweeperRunList[s.Name] = true + } else { + sweeperRunList[s.Name] = false + } + + return runE +} + const TestEnvVar = "TF_ACC" // TestProvider can be implemented by any ResourceProvider to provide custom diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go b/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go index c1564a2..856c675 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go @@ -41,6 +41,10 @@ type Provisioner struct { // information. ApplyFunc func(ctx context.Context) error + // ValidateFunc is a function for extended validation. This is optional + // and should be used when individual field validation is not enough. + ValidateFunc func(*ResourceData) ([]string, []error) + stopCtx context.Context stopCtxCancel context.CancelFunc stopOnce sync.Once @@ -117,8 +121,30 @@ func (p *Provisioner) Stop() error { return nil } -func (p *Provisioner) Validate(c *terraform.ResourceConfig) ([]string, []error) { - return schemaMap(p.Schema).Validate(c) +func (p *Provisioner) Validate(config *terraform.ResourceConfig) ([]string, []error) { + if err := p.InternalValidate(); err != nil { + return nil, []error{fmt.Errorf( + "Internal validation of the provisioner failed! This is always a bug\n"+ + "with the provisioner itself, and not a user issue. Please report\n"+ + "this bug:\n\n%s", err)} + } + w := []string{} + e := []error{} + if p.Schema != nil { + w2, e2 := schemaMap(p.Schema).Validate(config) + w = append(w, w2...) + e = append(e, e2...) + } + if p.ValidateFunc != nil { + data := &ResourceData{ + schema: p.Schema, + config: config, + } + w2, e2 := p.ValidateFunc(data) + w = append(w, w2...) + e = append(e, e2...) + } + return w, e } // Apply implementation of terraform.ResourceProvisioner interface. diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/schema.go b/vendor/github.com/hashicorp/terraform/helper/schema/schema.go index 32d1721..632672a 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/schema.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/schema.go @@ -1373,8 +1373,8 @@ func (m schemaMap) validateObject( k string, schema map[string]*Schema, c *terraform.ResourceConfig) ([]string, []error) { - raw, _ := c.GetRaw(k) - if _, ok := raw.(map[string]interface{}); !ok { + raw, _ := c.Get(k) + if _, ok := raw.(map[string]interface{}); !ok && !c.IsComputed(k) { return nil, []error{fmt.Errorf( "%s: expected object, got %s", k, reflect.ValueOf(raw).Kind())} diff --git a/vendor/github.com/hashicorp/terraform/helper/structure/expand_json.go b/vendor/github.com/hashicorp/terraform/helper/structure/expand_json.go deleted file mode 100644 index b3eb90f..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/structure/expand_json.go +++ /dev/null @@ -1,11 +0,0 @@ -package structure - -import "encoding/json" - -func ExpandJsonFromString(jsonString string) (map[string]interface{}, error) { - var result map[string]interface{} - - err := json.Unmarshal([]byte(jsonString), &result) - - return result, err -} diff --git a/vendor/github.com/hashicorp/terraform/helper/structure/flatten_json.go b/vendor/github.com/hashicorp/terraform/helper/structure/flatten_json.go deleted file mode 100644 index 578ad2e..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/structure/flatten_json.go +++ /dev/null @@ -1,16 +0,0 @@ -package structure - -import "encoding/json" - -func FlattenJsonToString(input map[string]interface{}) (string, error) { - if len(input) == 0 { - return "", nil - } - - result, err := json.Marshal(input) - if err != nil { - return "", err - } - - return string(result), nil -} diff --git a/vendor/github.com/hashicorp/terraform/helper/structure/normalize_json.go b/vendor/github.com/hashicorp/terraform/helper/structure/normalize_json.go deleted file mode 100644 index 3256b47..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/structure/normalize_json.go +++ /dev/null @@ -1,24 +0,0 @@ -package structure - -import "encoding/json" - -// Takes a value containing JSON string and passes it through -// the JSON parser to normalize it, returns either a parsing -// error or normalized JSON string. -func NormalizeJsonString(jsonString interface{}) (string, error) { - var j interface{} - - if jsonString == nil || jsonString.(string) == "" { - return "", nil - } - - s := jsonString.(string) - - err := json.Unmarshal([]byte(s), &j) - if err != nil { - return s, err - } - - bytes, _ := json.Marshal(j) - return string(bytes[:]), nil -} diff --git a/vendor/github.com/hashicorp/terraform/helper/structure/suppress_json_diff.go b/vendor/github.com/hashicorp/terraform/helper/structure/suppress_json_diff.go deleted file mode 100644 index 46f794a..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/structure/suppress_json_diff.go +++ /dev/null @@ -1,21 +0,0 @@ -package structure - -import ( - "reflect" - - "github.com/hashicorp/terraform/helper/schema" -) - -func SuppressJsonDiff(k, old, new string, d *schema.ResourceData) bool { - oldMap, err := ExpandJsonFromString(old) - if err != nil { - return false - } - - newMap, err := ExpandJsonFromString(new) - if err != nil { - return false - } - - return reflect.DeepEqual(oldMap, newMap) -} diff --git a/vendor/github.com/hashicorp/terraform/helper/validation/validation.go b/vendor/github.com/hashicorp/terraform/helper/validation/validation.go deleted file mode 100644 index 7b894f5..0000000 --- a/vendor/github.com/hashicorp/terraform/helper/validation/validation.go +++ /dev/null @@ -1,108 +0,0 @@ -package validation - -import ( - "fmt" - "net" - "strings" - - "github.com/hashicorp/terraform/helper/schema" - "github.com/hashicorp/terraform/helper/structure" -) - -// IntBetween returns a SchemaValidateFunc which tests if the provided value -// is of type int and is between min and max (inclusive) -func IntBetween(min, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(int) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be int", k)) - return - } - - if v < min || v > max { - es = append(es, fmt.Errorf("expected %s to be in the range (%d - %d), got %d", k, min, max, v)) - return - } - - return - } -} - -// StringInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type string and matches the value of an element in the valid slice -// will test with in lower case if ignoreCase is true -func StringInSlice(valid []string, ignoreCase bool) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - - for _, str := range valid { - if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { - return - } - } - - es = append(es, fmt.Errorf("expected %s to be one of %v, got %s", k, valid, v)) - return - } -} - -// StringLenBetween returns a SchemaValidateFunc which tests if the provided value -// is of type string and has length between min and max (inclusive) -func StringLenBetween(min, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - if len(v) < min || len(v) > max { - es = append(es, fmt.Errorf("expected length of %s to be in the range (%d - %d), got %s", k, min, max, v)) - } - return - } -} - -// CIDRNetwork returns a SchemaValidateFunc which tests if the provided value -// is of type string, is in valid CIDR network notation, and has significant bits between min and max (inclusive) -func CIDRNetwork(min, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(string) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be string", k)) - return - } - - _, ipnet, err := net.ParseCIDR(v) - if err != nil { - es = append(es, fmt.Errorf( - "expected %s to contain a valid CIDR, got: %s with err: %s", k, v, err)) - return - } - - if ipnet == nil || v != ipnet.String() { - es = append(es, fmt.Errorf( - "expected %s to contain a valid network CIDR, expected %s, got %s", - k, ipnet, v)) - } - - sigbits, _ := ipnet.Mask.Size() - if sigbits < min || sigbits > max { - es = append(es, fmt.Errorf( - "expected %q to contain a network CIDR with between %d and %d significant bits, got: %d", - k, min, max, sigbits)) - } - - return - } -} - -func ValidateJsonString(v interface{}, k string) (ws []string, errors []error) { - if _, err := structure.NormalizeJsonString(v); err != nil { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) - } - return -} -- cgit v1.2.3