Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | package matchers |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "reflect" |
| 6 | |
| 7 | "github.com/onsi/gomega/format" |
| 8 | ) |
| 9 | |
| 10 | type AssignableToTypeOfMatcher struct { |
| 11 | Expected interface{} |
| 12 | } |
| 13 | |
| 14 | func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) { |
| 15 | if actual == nil && matcher.Expected == nil { |
| 16 | return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") |
| 17 | } else if matcher.Expected == nil { |
| 18 | return false, fmt.Errorf("Refusing to compare type to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") |
| 19 | } else if actual == nil { |
| 20 | return false, nil |
| 21 | } |
| 22 | |
| 23 | actualType := reflect.TypeOf(actual) |
| 24 | expectedType := reflect.TypeOf(matcher.Expected) |
| 25 | |
| 26 | return actualType.AssignableTo(expectedType), nil |
| 27 | } |
| 28 | |
| 29 | func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual interface{}) string { |
| 30 | return format.Message(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)) |
| 31 | } |
| 32 | |
| 33 | func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual interface{}) string { |
| 34 | return format.Message(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)) |
| 35 | } |