github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/logentries/expect/expect.go (about)

     1  package test
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/hashicorp/terraform/helper/resource"
     6  	"github.com/hashicorp/terraform/terraform"
     7  	"reflect"
     8  	"regexp"
     9  )
    10  
    11  type TestExistsCheckFactoryFunc func(resource string, fact interface{}) resource.TestCheckFunc
    12  
    13  type TestExpectValue interface {
    14  	Execute(val interface{}) error
    15  	String() string
    16  }
    17  
    18  func TestCheckResourceExpectation(res string, fact interface{}, existsFunc TestExistsCheckFactoryFunc, expectation map[string]TestExpectValue) resource.TestCheckFunc {
    19  	return func(s *terraform.State) error {
    20  		if err := existsFunc(res, fact)(s); err != nil {
    21  			return fmt.Errorf("Expectation existence check error: %s", err)
    22  		}
    23  
    24  		value := reflect.ValueOf(fact).Elem()
    25  		for i := 0; i < value.NumField(); i++ {
    26  			t := value.Type().Field(i).Tag
    27  			tv := t.Get("tfresource")
    28  
    29  			// TODO: Support data types other than string
    30  			fv := value.Field(i).Interface().(string)
    31  			if expect, ok := expectation[tv]; ok {
    32  				if err := expect.Execute(fv); err != nil {
    33  					return fmt.Errorf("Expected %s, got \"%s\" (for %s)", expectation[tv], fv, tv)
    34  				}
    35  			}
    36  		}
    37  		return nil
    38  	}
    39  }
    40  
    41  type RegexTestExpectValue struct {
    42  	Value interface{}
    43  	TestExpectValue
    44  }
    45  
    46  func (t *RegexTestExpectValue) Execute(val interface{}) error {
    47  	expr := t.Value.(string)
    48  	if !regexp.MustCompile(expr).MatchString(val.(string)) {
    49  		return fmt.Errorf("Expected regexp match for \"%s\": %s", expr, val)
    50  	}
    51  	return nil
    52  }
    53  
    54  func (t *RegexTestExpectValue) String() string {
    55  	return fmt.Sprintf("regex[%s]", t.Value.(string))
    56  }
    57  
    58  func RegexMatches(exp string) TestExpectValue {
    59  	return &RegexTestExpectValue{Value: exp}
    60  }
    61  
    62  type EqualsTestExpectValue struct {
    63  	Value interface{}
    64  	TestExpectValue
    65  }
    66  
    67  func (t *EqualsTestExpectValue) Execute(val interface{}) error {
    68  	expr := t.Value.(string)
    69  	if val.(string) != t.Value.(string) {
    70  		return fmt.Errorf("Expected %s and %s to be equal", expr, val)
    71  	}
    72  	return nil
    73  }
    74  
    75  func (t *EqualsTestExpectValue) String() string {
    76  	return fmt.Sprintf("equals[%s]", t.Value.(string))
    77  }
    78  
    79  func Equals(exp string) TestExpectValue {
    80  	return &EqualsTestExpectValue{Value: exp}
    81  }