Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | package matchers |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "regexp" |
| 6 | |
| 7 | "github.com/onsi/gomega/format" |
| 8 | ) |
| 9 | |
| 10 | type MatchRegexpMatcher struct { |
| 11 | Regexp string |
| 12 | Args []interface{} |
| 13 | } |
| 14 | |
| 15 | func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err error) { |
| 16 | actualString, ok := toString(actual) |
| 17 | if !ok { |
| 18 | return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1)) |
| 19 | } |
| 20 | |
| 21 | match, err := regexp.Match(matcher.regexp(), []byte(actualString)) |
| 22 | if err != nil { |
| 23 | return false, fmt.Errorf("RegExp match failed to compile with error:\n\t%s", err.Error()) |
| 24 | } |
| 25 | |
| 26 | return match, nil |
| 27 | } |
| 28 | |
| 29 | func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) { |
| 30 | return format.Message(actual, "to match regular expression", matcher.regexp()) |
| 31 | } |
| 32 | |
| 33 | func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) { |
| 34 | return format.Message(actual, "not to match regular expression", matcher.regexp()) |
| 35 | } |
| 36 | |
| 37 | func (matcher *MatchRegexpMatcher) regexp() string { |
| 38 | re := matcher.Regexp |
| 39 | if len(matcher.Args) > 0 { |
| 40 | re = fmt.Sprintf(matcher.Regexp, matcher.Args...) |
| 41 | } |
| 42 | return re |
| 43 | } |