| 1 | // Copyright (c) The EfficientGo Authors. |
| 2 | // Licensed under the Apache License 2.0. |
| 3 | |
| 4 | package testutil |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "path/filepath" |
| 9 | "reflect" |
| 10 | "runtime" |
| 11 | "runtime/debug" |
| 12 | "testing" |
| 13 | |
| 14 | "github.com/davecgh/go-spew/spew" |
| 15 | "github.com/efficientgo/core/errors" |
| 16 | "github.com/efficientgo/core/testutil/internal" |
| 17 | "github.com/google/go-cmp/cmp" |
| 18 | ) |
| 19 | |
| 20 | const limitOfElemChars = 1e3 |
| 21 | |
| 22 | func withLimitf(f string, v ...interface{}) string { |
| 23 | s := fmt.Sprintf(f, v...) |
| 24 | if len(s) > limitOfElemChars { |
| 25 | return s[:limitOfElemChars] + "...(output trimmed)" |
| 26 | } |
| 27 | return s |
| 28 | } |
| 29 | |
| 30 | // Assert fails the test if the condition is false. |
| 31 | func Assert(tb testing.TB, condition bool, v ...interface{}) { |
| 32 | tb.Helper() |
| 33 | if condition { |
| 34 | return |
| 35 | } |
| 36 | _, file, line, _ := runtime.Caller(1) |
| 37 | |
| 38 | var msg string |
| 39 | if len(v) > 0 { |
| 40 | msg = fmt.Sprintf(v[0].(string), v[1:]...) |
| 41 | } |
| 42 | tb.Fatalf("\033[31m%s:%d: \"%s\"\033[39m\n\n", filepath.Base(file), line, withLimitf(msg)) |
| 43 | } |
| 44 | |
| 45 | // Ok fails the test if an err is not nil. |
| 46 | func Ok(tb testing.TB, err error, v ...interface{}) { |
| 47 | tb.Helper() |
| 48 | if err == nil { |
| 49 | return |
| 50 | } |
| 51 | _, file, line, _ := runtime.Caller(1) |
| 52 | |
| 53 | var msg string |
| 54 | if len(v) > 0 { |
| 55 | msg = fmt.Sprintf(v[0].(string), v[1:]...) |
| 56 | } |
| 57 | tb.Fatalf("\033[31m%s:%d: \"%s\"\n\n unexpected error: %s\033[39m\n\n", filepath.Base(file), line, withLimitf(msg), withLimitf(err.Error())) |
| 58 | } |
| 59 | |
| 60 | // NotOk fails the test if an err is nil. |
| 61 | func NotOk(tb testing.TB, err error, v ...interface{}) { |
| 62 | tb.Helper() |
| 63 | if err != nil { |
| 64 | return |
| 65 | } |
| 66 | _, file, line, _ := runtime.Caller(1) |
| 67 | |
| 68 | var msg string |
| 69 | if len(v) > 0 { |
| 70 | msg = fmt.Sprintf(v[0].(string), v[1:]...) |
| 71 | } |
| 72 | tb.Fatalf("\033[31m%s:%d: \"%s\"\n\n expected error, got nothing \033[39m\n\n", filepath.Base(file), line, withLimitf(msg)) |
| 73 | } |
| 74 | |
| 75 | // Equals fails the test if exp is not equal to act. |
| 76 | func Equals(tb testing.TB, exp, act interface{}, v ...interface{}) { |
| 77 | tb.Helper() |
| 78 | if reflect.DeepEqual(exp, act) { |
| 79 | return |
| 80 | } |
| 81 | fatalNotEqual(tb, exp, act, v...) |
| 82 | } |
| 83 | |
| 84 | func fatalNotEqual(tb testing.TB, exp, act interface{}, v ...interface{}) { |
| 85 | _, file, line, _ := runtime.Caller(2) |
| 86 | |
| 87 | var msg string |
| 88 | if len(v) > 0 { |
| 89 | msg = fmt.Sprintf(v[0].(string), v[1:]...) |
| 90 | } |
| 91 | tb.Fatalf( |
| 92 | "\033[31m%s:%d: \"%s\"\n\n\texp: %s\n\n\tgot: %s%s\033[39m\n\n", |
| 93 | filepath.Base(file), line, withLimitf(msg), withLimitf("%#v", exp), withLimitf("%#v", act), withLimitf(diff(exp, act)), |
| 94 | ) |
| 95 | } |
| 96 | |
| 97 | type goCmp struct { |
| 98 | opts cmp.Options |
| 99 | } |
| 100 | |
| 101 | // WithGoCmp allows specifying options and using https://github.com/google/go-cmp |
| 102 | // for equality comparisons. The compatibility guarantee of this function's arguments |
| 103 | // are the same as go-cmp (no guarantee due to v0.x). |
| 104 | func WithGoCmp(opts ...cmp.Option) goCmp { |
| 105 | return goCmp{opts: opts} |
| 106 | } |
| 107 | |
| 108 | // Equals uses go-cmp for comparing equality between two structs, and can be used with |
| 109 | // various options defined in go-cmp/cmp and go-cmp/cmp/cmpopts. |
| 110 | func (o goCmp) Equals(tb testing.TB, exp, act interface{}, v ...interface{}) { |
| 111 | tb.Helper() |
| 112 | if cmp.Equal(exp, act, o.opts) { |
| 113 | return |
| 114 | } |
| 115 | fatalNotEqual(tb, exp, act, v...) |
| 116 | } |
| 117 | |
| 118 | // FaultOrPanicToErr returns error if panic of fault was triggered during execution of function. |
| 119 | func FaultOrPanicToErr(f func()) (err error) { |
| 120 | // Set this go routine to panic on segfault to allow asserting on those. |
| 121 | debug.SetPanicOnFault(true) |
| 122 | defer func() { |
| 123 | if r := recover(); r != nil { |
| 124 | err = errors.Newf("invoked function panicked or caused segmentation fault: %v", r) |
| 125 | } |
| 126 | debug.SetPanicOnFault(false) |
| 127 | }() |
| 128 | |
| 129 | f() |
| 130 | |
| 131 | return err |
| 132 | } |
| 133 | |
| 134 | // ContainsStringSlice fails the test if needle is not contained within haystack, if haystack or needle is |
| 135 | // an empty slice, or if needle is longer than haystack. |
| 136 | func ContainsStringSlice(tb testing.TB, haystack, needle []string) { |
| 137 | _, file, line, _ := runtime.Caller(1) |
| 138 | |
| 139 | if !contains(haystack, needle) { |
| 140 | tb.Fatalf("\033[31m%s:%d: %s does not contain %s\033[39m\n\n", filepath.Base(file), line, withLimitf("%#v", haystack), withLimitf("%#v", needle)) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | func contains(haystack, needle []string) bool { |
| 145 | if len(haystack) == 0 || len(needle) == 0 { |
| 146 | return false |
| 147 | } |
| 148 | |
| 149 | if len(haystack) < len(needle) { |
| 150 | return false |
| 151 | } |
| 152 | |
| 153 | for i := 0; i < len(haystack); i++ { |
| 154 | outer := i |
| 155 | |
| 156 | for j := 0; j < len(needle); j++ { |
| 157 | // End of the haystack but not the end of the needle, end |
| 158 | if outer == len(haystack) { |
| 159 | return false |
| 160 | } |
| 161 | |
| 162 | // No match, try the next index of the haystack |
| 163 | if haystack[outer] != needle[j] { |
| 164 | break |
| 165 | } |
| 166 | |
| 167 | // End of the needle and it still matches, end |
| 168 | if j == len(needle)-1 { |
| 169 | return true |
| 170 | } |
| 171 | |
| 172 | // This element matches between the two slices, try the next one |
| 173 | outer++ |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | return false |
| 178 | } |
| 179 | |
| 180 | func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { |
| 181 | t := reflect.TypeOf(v) |
| 182 | k := t.Kind() |
| 183 | |
| 184 | if k == reflect.Ptr { |
| 185 | t = t.Elem() |
| 186 | k = t.Kind() |
| 187 | } |
| 188 | return t, k |
| 189 | } |
| 190 | |
| 191 | // diff returns a diff of both values as long as both are of the same type and |
| 192 | // are a struct, map, slice, array or string. Otherwise it returns an empty string. |
| 193 | func diff(expected interface{}, actual interface{}) string { |
| 194 | if expected == nil || actual == nil { |
| 195 | return "" |
| 196 | } |
| 197 | |
| 198 | et, ek := typeAndKind(expected) |
| 199 | at, _ := typeAndKind(actual) |
| 200 | if et != at { |
| 201 | return "" |
| 202 | } |
| 203 | |
| 204 | if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String { |
| 205 | return "" |
| 206 | } |
| 207 | |
| 208 | var e, a string |
| 209 | c := spew.ConfigState{ |
| 210 | Indent: " ", |
| 211 | DisablePointerAddresses: true, |
| 212 | DisableCapacities: true, |
| 213 | SortKeys: true, |
| 214 | } |
| 215 | if et != reflect.TypeOf("") { |
| 216 | e = c.Sdump(expected) |
| 217 | a = c.Sdump(actual) |
| 218 | } else { |
| 219 | e = reflect.ValueOf(expected).String() |
| 220 | a = reflect.ValueOf(actual).String() |
| 221 | } |
| 222 | |
| 223 | diff, _ := internal.GetUnifiedDiffString(internal.UnifiedDiff{ |
| 224 | A: internal.SplitLines(e), |
| 225 | B: internal.SplitLines(a), |
| 226 | FromFile: "Expected", |
| 227 | FromDate: "", |
| 228 | ToFile: "Actual", |
| 229 | ToDate: "", |
| 230 | Context: 1, |
| 231 | }) |
| 232 | return "\n\nDiff:\n" + diff |
| 233 | } |