github.com/rakutentech/cli@v6.12.5-0.20151006231303-24468b65536e+incompatible/testhelpers/matchers/be_in_display_order.go (about) 1 package matchers 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/onsi/gomega" 8 ) 9 10 type OrderMatcher struct { 11 expected [][]string 12 failedText string 13 } 14 15 func BeInDisplayOrder(substrings ...[]string) gomega.OmegaMatcher { 16 return &OrderMatcher{ 17 expected: substrings, 18 } 19 } 20 21 func (matcher *OrderMatcher) Match(actualStr interface{}) (success bool, err error) { 22 actual, ok := actualStr.([]string) 23 if !ok { 24 return false, nil 25 } 26 27 //loop and match, stop at last actual[0] line 28 for len(actual) > 1 { 29 if matched, msg := matchSingleLine(actual[0], matcher.expected[0]); matched { 30 if len(matcher.expected) == 1 { 31 return true, nil //no more expected to match, all passed 32 } 33 matcher.expected = matcher.expected[1:] 34 } else if msg != "" { 35 matcher.failedText = msg 36 return false, nil 37 } 38 actual = actual[1:] 39 } 40 41 //match the last actual line with the rest of expected 42 matched, msg := matchSingleLine(actual[0], matcher.expected[0]) 43 if matched && len(matcher.expected) == 1 { 44 return true, nil 45 } else if msg != "" { 46 matcher.failedText = msg 47 return false, nil 48 } else if matched { 49 matcher.failedText = matcher.expected[1][0] 50 return false, nil 51 } 52 matcher.failedText = matcher.expected[0][0] 53 return false, nil 54 } 55 56 func matchSingleLine(actual string, expected []string) (bool, string) { 57 matched := false 58 for i, target := range expected { 59 if index := strings.Index(actual, target); index != -1 { 60 if i == len(expected)-1 { 61 return true, "" 62 } 63 matched = true 64 actual = actual[index+len(target):] 65 } else if matched { 66 return false, target 67 } else { 68 return false, "" 69 } 70 } 71 return false, "" 72 } 73 74 func (matcher *OrderMatcher) FailureMessage(actual interface{}) string { 75 actualStrings, ok := actual.([]string) 76 if !ok { 77 return fmt.Sprintf("Expected actual to be a slice of strings, but it's actually a %T", actual) 78 } 79 80 return fmt.Sprintf("expected to find \"%s\" in display order in actual:\n'%s'\n", matcher.failedText, strings.Join(actualStrings, "\n")) 81 } 82 83 func (matcher *OrderMatcher) NegatedFailureMessage(actual interface{}) string { 84 actualStrings, ok := actual.([]string) 85 if !ok { 86 return fmt.Sprintf("Expected actual to be a slice of strings, but it's actually a %T", actual) 87 } 88 return fmt.Sprintf("expected to not find strings in display order in actual:\n'%s'\n", strings.Join(actualStrings, "\n")) 89 }