blob: adac5db6b8ef0e60f47eebbbcb51bb618de5150f [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001package matchers
2
3import (
4 "fmt"
5 "regexp"
6
7 "github.com/onsi/gomega/format"
8)
9
10type MatchRegexpMatcher struct {
11 Regexp string
12 Args []interface{}
13}
14
15func (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
29func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) {
30 return format.Message(actual, "to match regular expression", matcher.regexp())
31}
32
33func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) {
34 return format.Message(actual, "not to match regular expression", matcher.regexp())
35}
36
37func (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}