github.com/petergtz/pegomock@v2.9.1-0.20230424204322-eb0e044013df+incompatible/panic_with_message_to_matcher_test.go (about) 1 package pegomock_test 2 3 import ( 4 "fmt" 5 "reflect" 6 7 "github.com/onsi/gomega/format" 8 "github.com/onsi/gomega/types" 9 "github.com/petergtz/pegomock/internal/verify" 10 ) 11 12 type PanicWithMessageToMatcher struct { 13 expectedWith types.GomegaMatcher 14 actualWith interface{} 15 } 16 17 func PanicWithMessageTo(object types.GomegaMatcher) types.GomegaMatcher { 18 verify.Argument(object != nil, "You must provide a non-nil object to PanicWith") 19 return &PanicWithMessageToMatcher{expectedWith: object} 20 } 21 22 func (matcher *PanicWithMessageToMatcher) Match(actual interface{}) (success bool, err error) { 23 if actual == nil { 24 return false, fmt.Errorf("PanicWithMatcher expects a non-nil actual.") 25 } 26 27 actualType := reflect.TypeOf(actual) 28 if actualType.Kind() != reflect.Func { 29 return false, fmt.Errorf("PanicWithMatcher expects a function. Got:\n%s", format.Object(actual, 1)) 30 } 31 if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) { 32 return false, fmt.Errorf("PanicWithMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1)) 33 } 34 35 success = false 36 defer func() { 37 if object := recover(); object != nil { 38 var e error 39 success, e = matcher.expectedWith.Match(object) 40 if e != nil { 41 // TODO is there something needed here? 42 } 43 if !success { 44 matcher.actualWith = object 45 } 46 } else { 47 matcher.actualWith = object 48 } 49 }() 50 51 reflect.ValueOf(actual).Call([]reflect.Value{}) 52 53 return 54 } 55 56 func (matcher *PanicWithMessageToMatcher) FailureMessage(actual interface{}) (message string) { 57 if matcher.actualWith == nil { 58 return format.Message(actual, "to panic") 59 } else { 60 return fmt.Sprintf("Panic message does not match.\n\n%v", matcher.expectedWith.FailureMessage(matcher.actualWith)) 61 } 62 } 63 64 func (matcher *PanicWithMessageToMatcher) NegatedFailureMessage(actual interface{}) (message string) { 65 panic("Not implemented") 66 }