github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/util/testhelpers/matchers/match_func_name.go (about)

     1  package matchers
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"runtime"
     7  
     8  	"github.com/onsi/gomega"
     9  )
    10  
    11  type FuncsByNameMatcher struct {
    12  	expected      []interface{}
    13  	actualNames   []string
    14  	expectedNames []string
    15  }
    16  
    17  func MatchFuncsByName(funcs ...interface{}) gomega.OmegaMatcher {
    18  	return &FuncsByNameMatcher{expected: funcs}
    19  }
    20  
    21  func (matcher *FuncsByNameMatcher) Match(actual interface{}) (success bool, err error) {
    22  	for _, fn := range matcher.expected {
    23  		// just to be safe
    24  		if v := reflect.ValueOf(fn); v.Kind() == reflect.Func {
    25  			name := runtime.FuncForPC(v.Pointer()).Name()
    26  			matcher.expectedNames = append(matcher.expectedNames, name)
    27  		} else {
    28  			return false, fmt.Errorf("MatchChangeAppFuncsByName: Expected must be a slice of functions, got %s", v.Type().Name())
    29  		}
    30  	}
    31  
    32  	if t := reflect.TypeOf(actual); t.Kind() != reflect.Slice {
    33  		return false, fmt.Errorf("MatchChangeAppFuncsByName: Actual must be a slice of functions, got %s", t.Name())
    34  	}
    35  
    36  	arr := reflect.ValueOf(actual)
    37  
    38  	for i := 0; i < arr.Len(); i++ {
    39  		elem := arr.Index(i)
    40  		if elem.Kind() != reflect.Func {
    41  			return false, fmt.Errorf("MatchChangeAppFuncsByName: Actual must be a slice of functions, got %s", elem.Type().Name())
    42  		}
    43  		matcher.actualNames = append(matcher.actualNames, runtime.FuncForPC(elem.Pointer()).Name())
    44  	}
    45  
    46  	return reflect.DeepEqual(matcher.actualNames, matcher.expectedNames), nil
    47  }
    48  
    49  func (matcher *FuncsByNameMatcher) FailureMessage(actual interface{}) string {
    50  	return fmt.Sprintf("Expected:\n %v\n to match actual:\n%v\n", matcher.expectedNames, matcher.actualNames)
    51  }
    52  
    53  func (matcher *FuncsByNameMatcher) NegatedFailureMessage(actual interface{}) string {
    54  	return fmt.Sprintf("Expected:\n %v\n not to match actual:\n%v\n", matcher.expectedNames, matcher.actualNames)
    55  }