panic_matcher.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package matchers
  2. import (
  3. "fmt"
  4. "reflect"
  5. "github.com/onsi/gomega/format"
  6. )
  7. type PanicMatcher struct {
  8. object interface{}
  9. }
  10. func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) {
  11. if actual == nil {
  12. return false, fmt.Errorf("PanicMatcher expects a non-nil actual.")
  13. }
  14. actualType := reflect.TypeOf(actual)
  15. if actualType.Kind() != reflect.Func {
  16. return false, fmt.Errorf("PanicMatcher expects a function. Got:\n%s", format.Object(actual, 1))
  17. }
  18. if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
  19. return false, fmt.Errorf("PanicMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1))
  20. }
  21. success = false
  22. defer func() {
  23. if e := recover(); e != nil {
  24. matcher.object = e
  25. success = true
  26. }
  27. }()
  28. reflect.ValueOf(actual).Call([]reflect.Value{})
  29. return
  30. }
  31. func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) {
  32. return format.Message(actual, "to panic")
  33. }
  34. func (matcher *PanicMatcher) NegatedFailureMessage(actual interface{}) (message string) {
  35. return format.Message(actual, fmt.Sprintf("not to panic, but panicked with\n%s", format.Object(matcher.object, 1)))
  36. }