forked from petergtz/pegomock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
panic_with_message_matcher_test.go
67 lines (55 loc) · 2.02 KB
/
panic_with_message_matcher_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package pegomock_test
import (
"fmt"
"reflect"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
"github.com/petergtz/pegomock/v4/internal/verify"
)
type PanicWithMatcher struct {
expectedWith interface{}
actualWith interface{}
}
func PanicWith(object interface{}) types.GomegaMatcher {
verify.Argument(object != nil, "You must provide a non-nil object to PanicWith")
return &PanicWithMatcher{expectedWith: object}
}
func (matcher *PanicWithMatcher) Match(actual interface{}) (success bool, err error) {
if actual == nil {
return false, fmt.Errorf("PanicWithMatcher expects a non-nil actual.")
}
actualType := reflect.TypeOf(actual)
if actualType.Kind() != reflect.Func {
return false, fmt.Errorf("PanicWithMatcher expects a function. Got:\n%s", format.Object(actual, 1))
}
if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
return false, fmt.Errorf("PanicWithMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1))
}
success = false
defer func() {
if object := recover(); object == matcher.expectedWith {
success = true
} else {
matcher.actualWith = object
}
}()
reflect.ValueOf(actual).Call([]reflect.Value{})
return
}
func (matcher *PanicWithMatcher) FailureMessage(actual interface{}) (message string) {
if matcher.actualWith == "" {
return format.Message(actual, "to panic")
} else {
// TODO: can we reuse format.Message somehow?
return fmt.Sprintf("Expected\n\t<func ()>: %v\n\tpanicking with <%T>: %v\n\nto panic with\n\t<%T>: %v",
actual, matcher.actualWith, matcher.actualWith, matcher.expectedWith, matcher.expectedWith)
}
}
func (matcher *PanicWithMatcher) NegatedFailureMessage(actual interface{}) (message string) {
if matcher.actualWith == "" {
return format.Message(actual, "not to panic")
} else {
return fmt.Sprintf("Expected\n\t<func ()>: %v\n\tpanicking with <%T>: %v\n\nnot to panic with\n\t<%T>: %v",
actual, matcher.actualWith, matcher.actualWith, matcher.expectedWith, matcher.expectedWith)
}
}