Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1 | package assert |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "math" |
| 10 | "os" |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 11 | "path/filepath" |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 12 | "reflect" |
| 13 | "regexp" |
| 14 | "runtime" |
| 15 | "runtime/debug" |
| 16 | "strings" |
| 17 | "time" |
| 18 | "unicode" |
| 19 | "unicode/utf8" |
| 20 | |
| 21 | "github.com/davecgh/go-spew/spew" |
| 22 | "github.com/pmezard/go-difflib/difflib" |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 23 | yaml "gopkg.in/yaml.v3" |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 24 | ) |
| 25 | |
| 26 | //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl" |
| 27 | |
| 28 | // TestingT is an interface wrapper around *testing.T |
| 29 | type TestingT interface { |
| 30 | Errorf(format string, args ...interface{}) |
| 31 | } |
| 32 | |
| 33 | // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful |
| 34 | // for table driven tests. |
| 35 | type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool |
| 36 | |
| 37 | // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful |
| 38 | // for table driven tests. |
| 39 | type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool |
| 40 | |
| 41 | // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful |
| 42 | // for table driven tests. |
| 43 | type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool |
| 44 | |
| 45 | // ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful |
| 46 | // for table driven tests. |
| 47 | type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool |
| 48 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 49 | // Comparison is a custom function that returns true on success and false on failure |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 50 | type Comparison func() (success bool) |
| 51 | |
| 52 | /* |
| 53 | Helper functions |
| 54 | */ |
| 55 | |
| 56 | // ObjectsAreEqual determines if two objects are considered equal. |
| 57 | // |
| 58 | // This function does no assertion of any kind. |
| 59 | func ObjectsAreEqual(expected, actual interface{}) bool { |
| 60 | if expected == nil || actual == nil { |
| 61 | return expected == actual |
| 62 | } |
| 63 | |
| 64 | exp, ok := expected.([]byte) |
| 65 | if !ok { |
| 66 | return reflect.DeepEqual(expected, actual) |
| 67 | } |
| 68 | |
| 69 | act, ok := actual.([]byte) |
| 70 | if !ok { |
| 71 | return false |
| 72 | } |
| 73 | if exp == nil || act == nil { |
| 74 | return exp == nil && act == nil |
| 75 | } |
| 76 | return bytes.Equal(exp, act) |
| 77 | } |
| 78 | |
| 79 | // ObjectsAreEqualValues gets whether two objects are equal, or if their |
| 80 | // values are equal. |
| 81 | func ObjectsAreEqualValues(expected, actual interface{}) bool { |
| 82 | if ObjectsAreEqual(expected, actual) { |
| 83 | return true |
| 84 | } |
| 85 | |
| 86 | actualType := reflect.TypeOf(actual) |
| 87 | if actualType == nil { |
| 88 | return false |
| 89 | } |
| 90 | expectedValue := reflect.ValueOf(expected) |
| 91 | if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { |
| 92 | // Attempt comparison after type conversion |
| 93 | return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) |
| 94 | } |
| 95 | |
| 96 | return false |
| 97 | } |
| 98 | |
| 99 | /* CallerInfo is necessary because the assert functions use the testing object |
| 100 | internally, causing it to print the file:line of the assert method, rather than where |
| 101 | the problem actually occurred in calling code.*/ |
| 102 | |
| 103 | // CallerInfo returns an array of strings containing the file and line number |
| 104 | // of each stack frame leading from the current test to the assert call that |
| 105 | // failed. |
| 106 | func CallerInfo() []string { |
| 107 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 108 | var pc uintptr |
| 109 | var ok bool |
| 110 | var file string |
| 111 | var line int |
| 112 | var name string |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 113 | |
| 114 | callers := []string{} |
| 115 | for i := 0; ; i++ { |
| 116 | pc, file, line, ok = runtime.Caller(i) |
| 117 | if !ok { |
| 118 | // The breaks below failed to terminate the loop, and we ran off the |
| 119 | // end of the call stack. |
| 120 | break |
| 121 | } |
| 122 | |
| 123 | // This is a huge edge case, but it will panic if this is the case, see #180 |
| 124 | if file == "<autogenerated>" { |
| 125 | break |
| 126 | } |
| 127 | |
| 128 | f := runtime.FuncForPC(pc) |
| 129 | if f == nil { |
| 130 | break |
| 131 | } |
| 132 | name = f.Name() |
| 133 | |
| 134 | // testing.tRunner is the standard library function that calls |
| 135 | // tests. Subtests are called directly by tRunner, without going through |
| 136 | // the Test/Benchmark/Example function that contains the t.Run calls, so |
| 137 | // with subtests we should break when we hit tRunner, without adding it |
| 138 | // to the list of callers. |
| 139 | if name == "testing.tRunner" { |
| 140 | break |
| 141 | } |
| 142 | |
| 143 | parts := strings.Split(file, "/") |
| 144 | file = parts[len(parts)-1] |
| 145 | if len(parts) > 1 { |
| 146 | dir := parts[len(parts)-2] |
| 147 | if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 148 | path, _ := filepath.Abs(file) |
| 149 | callers = append(callers, fmt.Sprintf("%s:%d", path, line)) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 150 | } |
| 151 | } |
| 152 | |
| 153 | // Drop the package |
| 154 | segments := strings.Split(name, ".") |
| 155 | name = segments[len(segments)-1] |
| 156 | if isTest(name, "Test") || |
| 157 | isTest(name, "Benchmark") || |
| 158 | isTest(name, "Example") { |
| 159 | break |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | return callers |
| 164 | } |
| 165 | |
| 166 | // Stolen from the `go test` tool. |
| 167 | // isTest tells whether name looks like a test (or benchmark, according to prefix). |
| 168 | // It is a Test (say) if there is a character after Test that is not a lower-case letter. |
| 169 | // We don't want TesticularCancer. |
| 170 | func isTest(name, prefix string) bool { |
| 171 | if !strings.HasPrefix(name, prefix) { |
| 172 | return false |
| 173 | } |
| 174 | if len(name) == len(prefix) { // "Test" is ok |
| 175 | return true |
| 176 | } |
khenaidoo | 7d3c558 | 2021-08-11 18:09:44 -0400 | [diff] [blame] | 177 | r, _ := utf8.DecodeRuneInString(name[len(prefix):]) |
| 178 | return !unicode.IsLower(r) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 179 | } |
| 180 | |
| 181 | func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { |
| 182 | if len(msgAndArgs) == 0 || msgAndArgs == nil { |
| 183 | return "" |
| 184 | } |
| 185 | if len(msgAndArgs) == 1 { |
| 186 | msg := msgAndArgs[0] |
| 187 | if msgAsStr, ok := msg.(string); ok { |
| 188 | return msgAsStr |
| 189 | } |
| 190 | return fmt.Sprintf("%+v", msg) |
| 191 | } |
| 192 | if len(msgAndArgs) > 1 { |
| 193 | return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) |
| 194 | } |
| 195 | return "" |
| 196 | } |
| 197 | |
| 198 | // Aligns the provided message so that all lines after the first line start at the same location as the first line. |
| 199 | // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). |
| 200 | // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the |
| 201 | // basis on which the alignment occurs). |
| 202 | func indentMessageLines(message string, longestLabelLen int) string { |
| 203 | outBuf := new(bytes.Buffer) |
| 204 | |
| 205 | for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { |
| 206 | // no need to align first line because it starts at the correct location (after the label) |
| 207 | if i != 0 { |
| 208 | // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab |
| 209 | outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") |
| 210 | } |
| 211 | outBuf.WriteString(scanner.Text()) |
| 212 | } |
| 213 | |
| 214 | return outBuf.String() |
| 215 | } |
| 216 | |
| 217 | type failNower interface { |
| 218 | FailNow() |
| 219 | } |
| 220 | |
| 221 | // FailNow fails test |
| 222 | func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { |
| 223 | if h, ok := t.(tHelper); ok { |
| 224 | h.Helper() |
| 225 | } |
| 226 | Fail(t, failureMessage, msgAndArgs...) |
| 227 | |
| 228 | // We cannot extend TestingT with FailNow() and |
| 229 | // maintain backwards compatibility, so we fallback |
| 230 | // to panicking when FailNow is not available in |
| 231 | // TestingT. |
| 232 | // See issue #263 |
| 233 | |
| 234 | if t, ok := t.(failNower); ok { |
| 235 | t.FailNow() |
| 236 | } else { |
| 237 | panic("test failed and t is missing `FailNow()`") |
| 238 | } |
| 239 | return false |
| 240 | } |
| 241 | |
| 242 | // Fail reports a failure through |
| 243 | func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { |
| 244 | if h, ok := t.(tHelper); ok { |
| 245 | h.Helper() |
| 246 | } |
| 247 | content := []labeledContent{ |
| 248 | {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, |
| 249 | {"Error", failureMessage}, |
| 250 | } |
| 251 | |
| 252 | // Add test name if the Go version supports it |
| 253 | if n, ok := t.(interface { |
| 254 | Name() string |
| 255 | }); ok { |
| 256 | content = append(content, labeledContent{"Test", n.Name()}) |
| 257 | } |
| 258 | |
| 259 | message := messageFromMsgAndArgs(msgAndArgs...) |
| 260 | if len(message) > 0 { |
| 261 | content = append(content, labeledContent{"Messages", message}) |
| 262 | } |
| 263 | |
| 264 | t.Errorf("\n%s", ""+labeledOutput(content...)) |
| 265 | |
| 266 | return false |
| 267 | } |
| 268 | |
| 269 | type labeledContent struct { |
| 270 | label string |
| 271 | content string |
| 272 | } |
| 273 | |
| 274 | // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: |
| 275 | // |
| 276 | // \t{{label}}:{{align_spaces}}\t{{content}}\n |
| 277 | // |
| 278 | // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. |
| 279 | // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this |
| 280 | // alignment is achieved, "\t{{content}}\n" is added for the output. |
| 281 | // |
| 282 | // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. |
| 283 | func labeledOutput(content ...labeledContent) string { |
| 284 | longestLabel := 0 |
| 285 | for _, v := range content { |
| 286 | if len(v.label) > longestLabel { |
| 287 | longestLabel = len(v.label) |
| 288 | } |
| 289 | } |
| 290 | var output string |
| 291 | for _, v := range content { |
| 292 | output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" |
| 293 | } |
| 294 | return output |
| 295 | } |
| 296 | |
| 297 | // Implements asserts that an object is implemented by the specified interface. |
| 298 | // |
| 299 | // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) |
| 300 | func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { |
| 301 | if h, ok := t.(tHelper); ok { |
| 302 | h.Helper() |
| 303 | } |
| 304 | interfaceType := reflect.TypeOf(interfaceObject).Elem() |
| 305 | |
| 306 | if object == nil { |
| 307 | return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) |
| 308 | } |
| 309 | if !reflect.TypeOf(object).Implements(interfaceType) { |
| 310 | return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) |
| 311 | } |
| 312 | |
| 313 | return true |
| 314 | } |
| 315 | |
| 316 | // IsType asserts that the specified objects are of the same type. |
| 317 | func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { |
| 318 | if h, ok := t.(tHelper); ok { |
| 319 | h.Helper() |
| 320 | } |
| 321 | |
| 322 | if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { |
| 323 | return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) |
| 324 | } |
| 325 | |
| 326 | return true |
| 327 | } |
| 328 | |
| 329 | // Equal asserts that two objects are equal. |
| 330 | // |
| 331 | // assert.Equal(t, 123, 123) |
| 332 | // |
| 333 | // Pointer variable equality is determined based on the equality of the |
| 334 | // referenced values (as opposed to the memory addresses). Function equality |
| 335 | // cannot be determined and will always fail. |
| 336 | func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 337 | if h, ok := t.(tHelper); ok { |
| 338 | h.Helper() |
| 339 | } |
| 340 | if err := validateEqualArgs(expected, actual); err != nil { |
| 341 | return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", |
| 342 | expected, actual, err), msgAndArgs...) |
| 343 | } |
| 344 | |
| 345 | if !ObjectsAreEqual(expected, actual) { |
| 346 | diff := diff(expected, actual) |
| 347 | expected, actual = formatUnequalValues(expected, actual) |
| 348 | return Fail(t, fmt.Sprintf("Not equal: \n"+ |
| 349 | "expected: %s\n"+ |
| 350 | "actual : %s%s", expected, actual, diff), msgAndArgs...) |
| 351 | } |
| 352 | |
| 353 | return true |
| 354 | |
| 355 | } |
| 356 | |
| 357 | // validateEqualArgs checks whether provided arguments can be safely used in the |
| 358 | // Equal/NotEqual functions. |
| 359 | func validateEqualArgs(expected, actual interface{}) error { |
| 360 | if expected == nil && actual == nil { |
| 361 | return nil |
| 362 | } |
| 363 | |
| 364 | if isFunction(expected) || isFunction(actual) { |
| 365 | return errors.New("cannot take func type as argument") |
| 366 | } |
| 367 | return nil |
| 368 | } |
| 369 | |
| 370 | // Same asserts that two pointers reference the same object. |
| 371 | // |
| 372 | // assert.Same(t, ptr1, ptr2) |
| 373 | // |
| 374 | // Both arguments must be pointer variables. Pointer variable sameness is |
| 375 | // determined based on the equality of both type and value. |
| 376 | func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 377 | if h, ok := t.(tHelper); ok { |
| 378 | h.Helper() |
| 379 | } |
| 380 | |
| 381 | if !samePointers(expected, actual) { |
| 382 | return Fail(t, fmt.Sprintf("Not same: \n"+ |
| 383 | "expected: %p %#v\n"+ |
| 384 | "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...) |
| 385 | } |
| 386 | |
| 387 | return true |
| 388 | } |
| 389 | |
| 390 | // NotSame asserts that two pointers do not reference the same object. |
| 391 | // |
| 392 | // assert.NotSame(t, ptr1, ptr2) |
| 393 | // |
| 394 | // Both arguments must be pointer variables. Pointer variable sameness is |
| 395 | // determined based on the equality of both type and value. |
| 396 | func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 397 | if h, ok := t.(tHelper); ok { |
| 398 | h.Helper() |
| 399 | } |
| 400 | |
| 401 | if samePointers(expected, actual) { |
| 402 | return Fail(t, fmt.Sprintf( |
| 403 | "Expected and actual point to the same object: %p %#v", |
| 404 | expected, expected), msgAndArgs...) |
| 405 | } |
| 406 | return true |
| 407 | } |
| 408 | |
| 409 | // samePointers compares two generic interface objects and returns whether |
| 410 | // they point to the same object |
| 411 | func samePointers(first, second interface{}) bool { |
| 412 | firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second) |
| 413 | if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr { |
| 414 | return false |
| 415 | } |
| 416 | |
| 417 | firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second) |
| 418 | if firstType != secondType { |
| 419 | return false |
| 420 | } |
| 421 | |
| 422 | // compare pointer addresses |
| 423 | return first == second |
| 424 | } |
| 425 | |
| 426 | // formatUnequalValues takes two values of arbitrary types and returns string |
| 427 | // representations appropriate to be presented to the user. |
| 428 | // |
| 429 | // If the values are not of like type, the returned strings will be prefixed |
| 430 | // with the type name, and the value will be enclosed in parenthesis similar |
| 431 | // to a type conversion in the Go grammar. |
| 432 | func formatUnequalValues(expected, actual interface{}) (e string, a string) { |
| 433 | if reflect.TypeOf(expected) != reflect.TypeOf(actual) { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 434 | return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)), |
| 435 | fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual)) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 436 | } |
| 437 | switch expected.(type) { |
| 438 | case time.Duration: |
| 439 | return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual) |
| 440 | } |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 441 | return truncatingFormat(expected), truncatingFormat(actual) |
| 442 | } |
| 443 | |
| 444 | // truncatingFormat formats the data and truncates it if it's too long. |
| 445 | // |
| 446 | // This helps keep formatted error messages lines from exceeding the |
| 447 | // bufio.MaxScanTokenSize max line length that the go testing framework imposes. |
| 448 | func truncatingFormat(data interface{}) string { |
| 449 | value := fmt.Sprintf("%#v", data) |
| 450 | max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed. |
| 451 | if len(value) > max { |
| 452 | value = value[0:max] + "<... truncated>" |
| 453 | } |
| 454 | return value |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 455 | } |
| 456 | |
| 457 | // EqualValues asserts that two objects are equal or convertable to the same types |
| 458 | // and equal. |
| 459 | // |
| 460 | // assert.EqualValues(t, uint32(123), int32(123)) |
| 461 | func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 462 | if h, ok := t.(tHelper); ok { |
| 463 | h.Helper() |
| 464 | } |
| 465 | |
| 466 | if !ObjectsAreEqualValues(expected, actual) { |
| 467 | diff := diff(expected, actual) |
| 468 | expected, actual = formatUnequalValues(expected, actual) |
| 469 | return Fail(t, fmt.Sprintf("Not equal: \n"+ |
| 470 | "expected: %s\n"+ |
| 471 | "actual : %s%s", expected, actual, diff), msgAndArgs...) |
| 472 | } |
| 473 | |
| 474 | return true |
| 475 | |
| 476 | } |
| 477 | |
| 478 | // Exactly asserts that two objects are equal in value and type. |
| 479 | // |
| 480 | // assert.Exactly(t, int32(123), int64(123)) |
| 481 | func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 482 | if h, ok := t.(tHelper); ok { |
| 483 | h.Helper() |
| 484 | } |
| 485 | |
| 486 | aType := reflect.TypeOf(expected) |
| 487 | bType := reflect.TypeOf(actual) |
| 488 | |
| 489 | if aType != bType { |
| 490 | return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) |
| 491 | } |
| 492 | |
| 493 | return Equal(t, expected, actual, msgAndArgs...) |
| 494 | |
| 495 | } |
| 496 | |
| 497 | // NotNil asserts that the specified object is not nil. |
| 498 | // |
| 499 | // assert.NotNil(t, err) |
| 500 | func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 501 | if !isNil(object) { |
| 502 | return true |
| 503 | } |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 504 | if h, ok := t.(tHelper); ok { |
| 505 | h.Helper() |
| 506 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 507 | return Fail(t, "Expected value not to be nil.", msgAndArgs...) |
| 508 | } |
| 509 | |
| 510 | // containsKind checks if a specified kind in the slice of kinds. |
| 511 | func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool { |
| 512 | for i := 0; i < len(kinds); i++ { |
| 513 | if kind == kinds[i] { |
| 514 | return true |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | return false |
| 519 | } |
| 520 | |
| 521 | // isNil checks if a specified object is nil or not, without Failing. |
| 522 | func isNil(object interface{}) bool { |
| 523 | if object == nil { |
| 524 | return true |
| 525 | } |
| 526 | |
| 527 | value := reflect.ValueOf(object) |
| 528 | kind := value.Kind() |
| 529 | isNilableKind := containsKind( |
| 530 | []reflect.Kind{ |
| 531 | reflect.Chan, reflect.Func, |
| 532 | reflect.Interface, reflect.Map, |
| 533 | reflect.Ptr, reflect.Slice}, |
| 534 | kind) |
| 535 | |
| 536 | if isNilableKind && value.IsNil() { |
| 537 | return true |
| 538 | } |
| 539 | |
| 540 | return false |
| 541 | } |
| 542 | |
| 543 | // Nil asserts that the specified object is nil. |
| 544 | // |
| 545 | // assert.Nil(t, err) |
| 546 | func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 547 | if isNil(object) { |
| 548 | return true |
| 549 | } |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 550 | if h, ok := t.(tHelper); ok { |
| 551 | h.Helper() |
| 552 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 553 | return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) |
| 554 | } |
| 555 | |
| 556 | // isEmpty gets whether the specified object is considered empty or not. |
| 557 | func isEmpty(object interface{}) bool { |
| 558 | |
| 559 | // get nil case out of the way |
| 560 | if object == nil { |
| 561 | return true |
| 562 | } |
| 563 | |
| 564 | objValue := reflect.ValueOf(object) |
| 565 | |
| 566 | switch objValue.Kind() { |
| 567 | // collection types are empty when they have no element |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 568 | case reflect.Chan, reflect.Map, reflect.Slice: |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 569 | return objValue.Len() == 0 |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 570 | // pointers are empty if nil or if the value they point to is empty |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 571 | case reflect.Ptr: |
| 572 | if objValue.IsNil() { |
| 573 | return true |
| 574 | } |
| 575 | deref := objValue.Elem().Interface() |
| 576 | return isEmpty(deref) |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 577 | // for all other types, compare against the zero value |
| 578 | // array types are empty when they match their zero-initialized state |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 579 | default: |
| 580 | zero := reflect.Zero(objValue.Type()) |
| 581 | return reflect.DeepEqual(object, zero.Interface()) |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either |
| 586 | // a slice or a channel with len == 0. |
| 587 | // |
| 588 | // assert.Empty(t, obj) |
| 589 | func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 590 | pass := isEmpty(object) |
| 591 | if !pass { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 592 | if h, ok := t.(tHelper); ok { |
| 593 | h.Helper() |
| 594 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 595 | Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) |
| 596 | } |
| 597 | |
| 598 | return pass |
| 599 | |
| 600 | } |
| 601 | |
| 602 | // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either |
| 603 | // a slice or a channel with len == 0. |
| 604 | // |
| 605 | // if assert.NotEmpty(t, obj) { |
| 606 | // assert.Equal(t, "two", obj[1]) |
| 607 | // } |
| 608 | func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 609 | pass := !isEmpty(object) |
| 610 | if !pass { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 611 | if h, ok := t.(tHelper); ok { |
| 612 | h.Helper() |
| 613 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 614 | Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) |
| 615 | } |
| 616 | |
| 617 | return pass |
| 618 | |
| 619 | } |
| 620 | |
| 621 | // getLen try to get length of object. |
| 622 | // return (false, 0) if impossible. |
| 623 | func getLen(x interface{}) (ok bool, length int) { |
| 624 | v := reflect.ValueOf(x) |
| 625 | defer func() { |
| 626 | if e := recover(); e != nil { |
| 627 | ok = false |
| 628 | } |
| 629 | }() |
| 630 | return true, v.Len() |
| 631 | } |
| 632 | |
| 633 | // Len asserts that the specified object has specific length. |
| 634 | // Len also fails if the object has a type that len() not accept. |
| 635 | // |
| 636 | // assert.Len(t, mySlice, 3) |
| 637 | func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { |
| 638 | if h, ok := t.(tHelper); ok { |
| 639 | h.Helper() |
| 640 | } |
| 641 | ok, l := getLen(object) |
| 642 | if !ok { |
| 643 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) |
| 644 | } |
| 645 | |
| 646 | if l != length { |
| 647 | return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) |
| 648 | } |
| 649 | return true |
| 650 | } |
| 651 | |
| 652 | // True asserts that the specified value is true. |
| 653 | // |
| 654 | // assert.True(t, myBool) |
| 655 | func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 656 | if !value { |
| 657 | if h, ok := t.(tHelper); ok { |
| 658 | h.Helper() |
| 659 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 660 | return Fail(t, "Should be true", msgAndArgs...) |
| 661 | } |
| 662 | |
| 663 | return true |
| 664 | |
| 665 | } |
| 666 | |
| 667 | // False asserts that the specified value is false. |
| 668 | // |
| 669 | // assert.False(t, myBool) |
| 670 | func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 671 | if value { |
| 672 | if h, ok := t.(tHelper); ok { |
| 673 | h.Helper() |
| 674 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 675 | return Fail(t, "Should be false", msgAndArgs...) |
| 676 | } |
| 677 | |
| 678 | return true |
| 679 | |
| 680 | } |
| 681 | |
| 682 | // NotEqual asserts that the specified values are NOT equal. |
| 683 | // |
| 684 | // assert.NotEqual(t, obj1, obj2) |
| 685 | // |
| 686 | // Pointer variable equality is determined based on the equality of the |
| 687 | // referenced values (as opposed to the memory addresses). |
| 688 | func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 689 | if h, ok := t.(tHelper); ok { |
| 690 | h.Helper() |
| 691 | } |
| 692 | if err := validateEqualArgs(expected, actual); err != nil { |
| 693 | return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", |
| 694 | expected, actual, err), msgAndArgs...) |
| 695 | } |
| 696 | |
| 697 | if ObjectsAreEqual(expected, actual) { |
| 698 | return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) |
| 699 | } |
| 700 | |
| 701 | return true |
| 702 | |
| 703 | } |
| 704 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 705 | // NotEqualValues asserts that two objects are not equal even when converted to the same type |
| 706 | // |
| 707 | // assert.NotEqualValues(t, obj1, obj2) |
| 708 | func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { |
| 709 | if h, ok := t.(tHelper); ok { |
| 710 | h.Helper() |
| 711 | } |
| 712 | |
| 713 | if ObjectsAreEqualValues(expected, actual) { |
| 714 | return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) |
| 715 | } |
| 716 | |
| 717 | return true |
| 718 | } |
| 719 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 720 | // containsElement try loop over the list check if the list includes the element. |
| 721 | // return (false, false) if impossible. |
| 722 | // return (true, false) if element was not found. |
| 723 | // return (true, true) if element was found. |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 724 | func containsElement(list interface{}, element interface{}) (ok, found bool) { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 725 | |
| 726 | listValue := reflect.ValueOf(list) |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 727 | listType := reflect.TypeOf(list) |
| 728 | if listType == nil { |
| 729 | return false, false |
| 730 | } |
| 731 | listKind := listType.Kind() |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 732 | defer func() { |
| 733 | if e := recover(); e != nil { |
| 734 | ok = false |
| 735 | found = false |
| 736 | } |
| 737 | }() |
| 738 | |
| 739 | if listKind == reflect.String { |
| 740 | elementValue := reflect.ValueOf(element) |
| 741 | return true, strings.Contains(listValue.String(), elementValue.String()) |
| 742 | } |
| 743 | |
| 744 | if listKind == reflect.Map { |
| 745 | mapKeys := listValue.MapKeys() |
| 746 | for i := 0; i < len(mapKeys); i++ { |
| 747 | if ObjectsAreEqual(mapKeys[i].Interface(), element) { |
| 748 | return true, true |
| 749 | } |
| 750 | } |
| 751 | return true, false |
| 752 | } |
| 753 | |
| 754 | for i := 0; i < listValue.Len(); i++ { |
| 755 | if ObjectsAreEqual(listValue.Index(i).Interface(), element) { |
| 756 | return true, true |
| 757 | } |
| 758 | } |
| 759 | return true, false |
| 760 | |
| 761 | } |
| 762 | |
| 763 | // Contains asserts that the specified string, list(array, slice...) or map contains the |
| 764 | // specified substring or element. |
| 765 | // |
| 766 | // assert.Contains(t, "Hello World", "World") |
| 767 | // assert.Contains(t, ["Hello", "World"], "World") |
| 768 | // assert.Contains(t, {"Hello": "World"}, "Hello") |
| 769 | func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { |
| 770 | if h, ok := t.(tHelper); ok { |
| 771 | h.Helper() |
| 772 | } |
| 773 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 774 | ok, found := containsElement(s, contains) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 775 | if !ok { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 776 | return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 777 | } |
| 778 | if !found { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 779 | return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 780 | } |
| 781 | |
| 782 | return true |
| 783 | |
| 784 | } |
| 785 | |
| 786 | // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the |
| 787 | // specified substring or element. |
| 788 | // |
| 789 | // assert.NotContains(t, "Hello World", "Earth") |
| 790 | // assert.NotContains(t, ["Hello", "World"], "Earth") |
| 791 | // assert.NotContains(t, {"Hello": "World"}, "Earth") |
| 792 | func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { |
| 793 | if h, ok := t.(tHelper); ok { |
| 794 | h.Helper() |
| 795 | } |
| 796 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 797 | ok, found := containsElement(s, contains) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 798 | if !ok { |
| 799 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) |
| 800 | } |
| 801 | if found { |
| 802 | return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) |
| 803 | } |
| 804 | |
| 805 | return true |
| 806 | |
| 807 | } |
| 808 | |
| 809 | // Subset asserts that the specified list(array, slice...) contains all |
| 810 | // elements given in the specified subset(array, slice...). |
| 811 | // |
| 812 | // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") |
| 813 | func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { |
| 814 | if h, ok := t.(tHelper); ok { |
| 815 | h.Helper() |
| 816 | } |
| 817 | if subset == nil { |
| 818 | return true // we consider nil to be equal to the nil set |
| 819 | } |
| 820 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 821 | defer func() { |
| 822 | if e := recover(); e != nil { |
| 823 | ok = false |
| 824 | } |
| 825 | }() |
| 826 | |
| 827 | listKind := reflect.TypeOf(list).Kind() |
| 828 | subsetKind := reflect.TypeOf(subset).Kind() |
| 829 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 830 | if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 831 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) |
| 832 | } |
| 833 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 834 | if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 835 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) |
| 836 | } |
| 837 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 838 | subsetValue := reflect.ValueOf(subset) |
| 839 | if subsetKind == reflect.Map && listKind == reflect.Map { |
| 840 | listValue := reflect.ValueOf(list) |
| 841 | subsetKeys := subsetValue.MapKeys() |
| 842 | |
| 843 | for i := 0; i < len(subsetKeys); i++ { |
| 844 | subsetKey := subsetKeys[i] |
| 845 | subsetElement := subsetValue.MapIndex(subsetKey).Interface() |
| 846 | listElement := listValue.MapIndex(subsetKey).Interface() |
| 847 | |
| 848 | if !ObjectsAreEqual(subsetElement, listElement) { |
| 849 | return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, subsetElement), msgAndArgs...) |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | return true |
| 854 | } |
| 855 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 856 | for i := 0; i < subsetValue.Len(); i++ { |
| 857 | element := subsetValue.Index(i).Interface() |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 858 | ok, found := containsElement(list, element) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 859 | if !ok { |
| 860 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) |
| 861 | } |
| 862 | if !found { |
| 863 | return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | return true |
| 868 | } |
| 869 | |
| 870 | // NotSubset asserts that the specified list(array, slice...) contains not all |
| 871 | // elements given in the specified subset(array, slice...). |
| 872 | // |
| 873 | // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") |
| 874 | func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { |
| 875 | if h, ok := t.(tHelper); ok { |
| 876 | h.Helper() |
| 877 | } |
| 878 | if subset == nil { |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 879 | return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 880 | } |
| 881 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 882 | defer func() { |
| 883 | if e := recover(); e != nil { |
| 884 | ok = false |
| 885 | } |
| 886 | }() |
| 887 | |
| 888 | listKind := reflect.TypeOf(list).Kind() |
| 889 | subsetKind := reflect.TypeOf(subset).Kind() |
| 890 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 891 | if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 892 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) |
| 893 | } |
| 894 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 895 | if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 896 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) |
| 897 | } |
| 898 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 899 | subsetValue := reflect.ValueOf(subset) |
| 900 | if subsetKind == reflect.Map && listKind == reflect.Map { |
| 901 | listValue := reflect.ValueOf(list) |
| 902 | subsetKeys := subsetValue.MapKeys() |
| 903 | |
| 904 | for i := 0; i < len(subsetKeys); i++ { |
| 905 | subsetKey := subsetKeys[i] |
| 906 | subsetElement := subsetValue.MapIndex(subsetKey).Interface() |
| 907 | listElement := listValue.MapIndex(subsetKey).Interface() |
| 908 | |
| 909 | if !ObjectsAreEqual(subsetElement, listElement) { |
| 910 | return true |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) |
| 915 | } |
| 916 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 917 | for i := 0; i < subsetValue.Len(); i++ { |
| 918 | element := subsetValue.Index(i).Interface() |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 919 | ok, found := containsElement(list, element) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 920 | if !ok { |
| 921 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) |
| 922 | } |
| 923 | if !found { |
| 924 | return true |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) |
| 929 | } |
| 930 | |
| 931 | // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified |
| 932 | // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, |
| 933 | // the number of appearances of each of them in both lists should match. |
| 934 | // |
| 935 | // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) |
| 936 | func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { |
| 937 | if h, ok := t.(tHelper); ok { |
| 938 | h.Helper() |
| 939 | } |
| 940 | if isEmpty(listA) && isEmpty(listB) { |
| 941 | return true |
| 942 | } |
| 943 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 944 | if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) { |
| 945 | return false |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 946 | } |
| 947 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 948 | extraA, extraB := diffLists(listA, listB) |
| 949 | |
| 950 | if len(extraA) == 0 && len(extraB) == 0 { |
| 951 | return true |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 952 | } |
| 953 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 954 | return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...) |
| 955 | } |
| 956 | |
| 957 | // isList checks that the provided value is array or slice. |
| 958 | func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) { |
| 959 | kind := reflect.TypeOf(list).Kind() |
| 960 | if kind != reflect.Array && kind != reflect.Slice { |
| 961 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind), |
| 962 | msgAndArgs...) |
| 963 | } |
| 964 | return true |
| 965 | } |
| 966 | |
| 967 | // diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B. |
| 968 | // If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and |
| 969 | // 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored. |
| 970 | func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 971 | aValue := reflect.ValueOf(listA) |
| 972 | bValue := reflect.ValueOf(listB) |
| 973 | |
| 974 | aLen := aValue.Len() |
| 975 | bLen := bValue.Len() |
| 976 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 977 | // Mark indexes in bValue that we already used |
| 978 | visited := make([]bool, bLen) |
| 979 | for i := 0; i < aLen; i++ { |
| 980 | element := aValue.Index(i).Interface() |
| 981 | found := false |
| 982 | for j := 0; j < bLen; j++ { |
| 983 | if visited[j] { |
| 984 | continue |
| 985 | } |
| 986 | if ObjectsAreEqual(bValue.Index(j).Interface(), element) { |
| 987 | visited[j] = true |
| 988 | found = true |
| 989 | break |
| 990 | } |
| 991 | } |
| 992 | if !found { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 993 | extraA = append(extraA, element) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 994 | } |
| 995 | } |
| 996 | |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 997 | for j := 0; j < bLen; j++ { |
| 998 | if visited[j] { |
| 999 | continue |
| 1000 | } |
| 1001 | extraB = append(extraB, bValue.Index(j).Interface()) |
| 1002 | } |
| 1003 | |
| 1004 | return |
| 1005 | } |
| 1006 | |
| 1007 | func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string { |
| 1008 | var msg bytes.Buffer |
| 1009 | |
| 1010 | msg.WriteString("elements differ") |
| 1011 | if len(extraA) > 0 { |
| 1012 | msg.WriteString("\n\nextra elements in list A:\n") |
| 1013 | msg.WriteString(spewConfig.Sdump(extraA)) |
| 1014 | } |
| 1015 | if len(extraB) > 0 { |
| 1016 | msg.WriteString("\n\nextra elements in list B:\n") |
| 1017 | msg.WriteString(spewConfig.Sdump(extraB)) |
| 1018 | } |
| 1019 | msg.WriteString("\n\nlistA:\n") |
| 1020 | msg.WriteString(spewConfig.Sdump(listA)) |
| 1021 | msg.WriteString("\n\nlistB:\n") |
| 1022 | msg.WriteString(spewConfig.Sdump(listB)) |
| 1023 | |
| 1024 | return msg.String() |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1025 | } |
| 1026 | |
| 1027 | // Condition uses a Comparison to assert a complex condition. |
| 1028 | func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { |
| 1029 | if h, ok := t.(tHelper); ok { |
| 1030 | h.Helper() |
| 1031 | } |
| 1032 | result := comp() |
| 1033 | if !result { |
| 1034 | Fail(t, "Condition failed!", msgAndArgs...) |
| 1035 | } |
| 1036 | return result |
| 1037 | } |
| 1038 | |
| 1039 | // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics |
| 1040 | // methods, and represents a simple func that takes no arguments, and returns nothing. |
| 1041 | type PanicTestFunc func() |
| 1042 | |
| 1043 | // didPanic returns true if the function passed to it panics. Otherwise, it returns false. |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1044 | func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) { |
| 1045 | didPanic = true |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1046 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1047 | defer func() { |
| 1048 | message = recover() |
| 1049 | if didPanic { |
| 1050 | stack = string(debug.Stack()) |
| 1051 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1052 | }() |
| 1053 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1054 | // call the target function |
| 1055 | f() |
| 1056 | didPanic = false |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1057 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1058 | return |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1059 | } |
| 1060 | |
| 1061 | // Panics asserts that the code inside the specified PanicTestFunc panics. |
| 1062 | // |
| 1063 | // assert.Panics(t, func(){ GoCrazy() }) |
| 1064 | func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { |
| 1065 | if h, ok := t.(tHelper); ok { |
| 1066 | h.Helper() |
| 1067 | } |
| 1068 | |
| 1069 | if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic { |
| 1070 | return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) |
| 1071 | } |
| 1072 | |
| 1073 | return true |
| 1074 | } |
| 1075 | |
| 1076 | // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that |
| 1077 | // the recovered panic value equals the expected panic value. |
| 1078 | // |
| 1079 | // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) |
| 1080 | func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { |
| 1081 | if h, ok := t.(tHelper); ok { |
| 1082 | h.Helper() |
| 1083 | } |
| 1084 | |
| 1085 | funcDidPanic, panicValue, panickedStack := didPanic(f) |
| 1086 | if !funcDidPanic { |
| 1087 | return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) |
| 1088 | } |
| 1089 | if panicValue != expected { |
| 1090 | return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...) |
| 1091 | } |
| 1092 | |
| 1093 | return true |
| 1094 | } |
| 1095 | |
| 1096 | // PanicsWithError asserts that the code inside the specified PanicTestFunc |
| 1097 | // panics, and that the recovered panic value is an error that satisfies the |
| 1098 | // EqualError comparison. |
| 1099 | // |
| 1100 | // assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) |
| 1101 | func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool { |
| 1102 | if h, ok := t.(tHelper); ok { |
| 1103 | h.Helper() |
| 1104 | } |
| 1105 | |
| 1106 | funcDidPanic, panicValue, panickedStack := didPanic(f) |
| 1107 | if !funcDidPanic { |
| 1108 | return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) |
| 1109 | } |
| 1110 | panicErr, ok := panicValue.(error) |
| 1111 | if !ok || panicErr.Error() != errString { |
| 1112 | return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...) |
| 1113 | } |
| 1114 | |
| 1115 | return true |
| 1116 | } |
| 1117 | |
| 1118 | // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. |
| 1119 | // |
| 1120 | // assert.NotPanics(t, func(){ RemainCalm() }) |
| 1121 | func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { |
| 1122 | if h, ok := t.(tHelper); ok { |
| 1123 | h.Helper() |
| 1124 | } |
| 1125 | |
| 1126 | if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic { |
| 1127 | return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...) |
| 1128 | } |
| 1129 | |
| 1130 | return true |
| 1131 | } |
| 1132 | |
| 1133 | // WithinDuration asserts that the two times are within duration delta of each other. |
| 1134 | // |
| 1135 | // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) |
| 1136 | func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { |
| 1137 | if h, ok := t.(tHelper); ok { |
| 1138 | h.Helper() |
| 1139 | } |
| 1140 | |
| 1141 | dt := expected.Sub(actual) |
| 1142 | if dt < -delta || dt > delta { |
| 1143 | return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) |
| 1144 | } |
| 1145 | |
| 1146 | return true |
| 1147 | } |
| 1148 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1149 | // WithinRange asserts that a time is within a time range (inclusive). |
| 1150 | // |
| 1151 | // assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) |
| 1152 | func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool { |
| 1153 | if h, ok := t.(tHelper); ok { |
| 1154 | h.Helper() |
| 1155 | } |
| 1156 | |
| 1157 | if end.Before(start) { |
| 1158 | return Fail(t, "Start should be before end", msgAndArgs...) |
| 1159 | } |
| 1160 | |
| 1161 | if actual.Before(start) { |
| 1162 | return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is before the range", actual, start, end), msgAndArgs...) |
| 1163 | } else if actual.After(end) { |
| 1164 | return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is after the range", actual, start, end), msgAndArgs...) |
| 1165 | } |
| 1166 | |
| 1167 | return true |
| 1168 | } |
| 1169 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1170 | func toFloat(x interface{}) (float64, bool) { |
| 1171 | var xf float64 |
| 1172 | xok := true |
| 1173 | |
| 1174 | switch xn := x.(type) { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1175 | case uint: |
| 1176 | xf = float64(xn) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1177 | case uint8: |
| 1178 | xf = float64(xn) |
| 1179 | case uint16: |
| 1180 | xf = float64(xn) |
| 1181 | case uint32: |
| 1182 | xf = float64(xn) |
| 1183 | case uint64: |
| 1184 | xf = float64(xn) |
| 1185 | case int: |
| 1186 | xf = float64(xn) |
| 1187 | case int8: |
| 1188 | xf = float64(xn) |
| 1189 | case int16: |
| 1190 | xf = float64(xn) |
| 1191 | case int32: |
| 1192 | xf = float64(xn) |
| 1193 | case int64: |
| 1194 | xf = float64(xn) |
| 1195 | case float32: |
| 1196 | xf = float64(xn) |
| 1197 | case float64: |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1198 | xf = xn |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1199 | case time.Duration: |
| 1200 | xf = float64(xn) |
| 1201 | default: |
| 1202 | xok = false |
| 1203 | } |
| 1204 | |
| 1205 | return xf, xok |
| 1206 | } |
| 1207 | |
| 1208 | // InDelta asserts that the two numerals are within delta of each other. |
| 1209 | // |
| 1210 | // assert.InDelta(t, math.Pi, 22/7.0, 0.01) |
| 1211 | func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { |
| 1212 | if h, ok := t.(tHelper); ok { |
| 1213 | h.Helper() |
| 1214 | } |
| 1215 | |
| 1216 | af, aok := toFloat(expected) |
| 1217 | bf, bok := toFloat(actual) |
| 1218 | |
| 1219 | if !aok || !bok { |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1220 | return Fail(t, "Parameters must be numerical", msgAndArgs...) |
| 1221 | } |
| 1222 | |
| 1223 | if math.IsNaN(af) && math.IsNaN(bf) { |
| 1224 | return true |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1225 | } |
| 1226 | |
| 1227 | if math.IsNaN(af) { |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1228 | return Fail(t, "Expected must not be NaN", msgAndArgs...) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1229 | } |
| 1230 | |
| 1231 | if math.IsNaN(bf) { |
| 1232 | return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) |
| 1233 | } |
| 1234 | |
| 1235 | dt := af - bf |
| 1236 | if dt < -delta || dt > delta { |
| 1237 | return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) |
| 1238 | } |
| 1239 | |
| 1240 | return true |
| 1241 | } |
| 1242 | |
| 1243 | // InDeltaSlice is the same as InDelta, except it compares two slices. |
| 1244 | func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { |
| 1245 | if h, ok := t.(tHelper); ok { |
| 1246 | h.Helper() |
| 1247 | } |
| 1248 | if expected == nil || actual == nil || |
| 1249 | reflect.TypeOf(actual).Kind() != reflect.Slice || |
| 1250 | reflect.TypeOf(expected).Kind() != reflect.Slice { |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1251 | return Fail(t, "Parameters must be slice", msgAndArgs...) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1252 | } |
| 1253 | |
| 1254 | actualSlice := reflect.ValueOf(actual) |
| 1255 | expectedSlice := reflect.ValueOf(expected) |
| 1256 | |
| 1257 | for i := 0; i < actualSlice.Len(); i++ { |
| 1258 | result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) |
| 1259 | if !result { |
| 1260 | return result |
| 1261 | } |
| 1262 | } |
| 1263 | |
| 1264 | return true |
| 1265 | } |
| 1266 | |
| 1267 | // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. |
| 1268 | func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { |
| 1269 | if h, ok := t.(tHelper); ok { |
| 1270 | h.Helper() |
| 1271 | } |
| 1272 | if expected == nil || actual == nil || |
| 1273 | reflect.TypeOf(actual).Kind() != reflect.Map || |
| 1274 | reflect.TypeOf(expected).Kind() != reflect.Map { |
| 1275 | return Fail(t, "Arguments must be maps", msgAndArgs...) |
| 1276 | } |
| 1277 | |
| 1278 | expectedMap := reflect.ValueOf(expected) |
| 1279 | actualMap := reflect.ValueOf(actual) |
| 1280 | |
| 1281 | if expectedMap.Len() != actualMap.Len() { |
| 1282 | return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) |
| 1283 | } |
| 1284 | |
| 1285 | for _, k := range expectedMap.MapKeys() { |
| 1286 | ev := expectedMap.MapIndex(k) |
| 1287 | av := actualMap.MapIndex(k) |
| 1288 | |
| 1289 | if !ev.IsValid() { |
| 1290 | return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) |
| 1291 | } |
| 1292 | |
| 1293 | if !av.IsValid() { |
| 1294 | return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) |
| 1295 | } |
| 1296 | |
| 1297 | if !InDelta( |
| 1298 | t, |
| 1299 | ev.Interface(), |
| 1300 | av.Interface(), |
| 1301 | delta, |
| 1302 | msgAndArgs..., |
| 1303 | ) { |
| 1304 | return false |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | return true |
| 1309 | } |
| 1310 | |
| 1311 | func calcRelativeError(expected, actual interface{}) (float64, error) { |
| 1312 | af, aok := toFloat(expected) |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1313 | bf, bok := toFloat(actual) |
| 1314 | if !aok || !bok { |
| 1315 | return 0, fmt.Errorf("Parameters must be numerical") |
| 1316 | } |
| 1317 | if math.IsNaN(af) && math.IsNaN(bf) { |
| 1318 | return 0, nil |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1319 | } |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1320 | if math.IsNaN(af) { |
| 1321 | return 0, errors.New("expected value must not be NaN") |
| 1322 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1323 | if af == 0 { |
| 1324 | return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") |
| 1325 | } |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1326 | if math.IsNaN(bf) { |
| 1327 | return 0, errors.New("actual value must not be NaN") |
| 1328 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1329 | |
| 1330 | return math.Abs(af-bf) / math.Abs(af), nil |
| 1331 | } |
| 1332 | |
| 1333 | // InEpsilon asserts that expected and actual have a relative error less than epsilon |
| 1334 | func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { |
| 1335 | if h, ok := t.(tHelper); ok { |
| 1336 | h.Helper() |
| 1337 | } |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1338 | if math.IsNaN(epsilon) { |
| 1339 | return Fail(t, "epsilon must not be NaN") |
| 1340 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1341 | actualEpsilon, err := calcRelativeError(expected, actual) |
| 1342 | if err != nil { |
| 1343 | return Fail(t, err.Error(), msgAndArgs...) |
| 1344 | } |
| 1345 | if actualEpsilon > epsilon { |
| 1346 | return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ |
| 1347 | " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) |
| 1348 | } |
| 1349 | |
| 1350 | return true |
| 1351 | } |
| 1352 | |
| 1353 | // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. |
| 1354 | func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { |
| 1355 | if h, ok := t.(tHelper); ok { |
| 1356 | h.Helper() |
| 1357 | } |
| 1358 | if expected == nil || actual == nil || |
| 1359 | reflect.TypeOf(actual).Kind() != reflect.Slice || |
| 1360 | reflect.TypeOf(expected).Kind() != reflect.Slice { |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1361 | return Fail(t, "Parameters must be slice", msgAndArgs...) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1362 | } |
| 1363 | |
| 1364 | actualSlice := reflect.ValueOf(actual) |
| 1365 | expectedSlice := reflect.ValueOf(expected) |
| 1366 | |
| 1367 | for i := 0; i < actualSlice.Len(); i++ { |
| 1368 | result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) |
| 1369 | if !result { |
| 1370 | return result |
| 1371 | } |
| 1372 | } |
| 1373 | |
| 1374 | return true |
| 1375 | } |
| 1376 | |
| 1377 | /* |
| 1378 | Errors |
| 1379 | */ |
| 1380 | |
| 1381 | // NoError asserts that a function returned no error (i.e. `nil`). |
| 1382 | // |
| 1383 | // actualObj, err := SomeFunction() |
| 1384 | // if assert.NoError(t, err) { |
| 1385 | // assert.Equal(t, expectedObj, actualObj) |
| 1386 | // } |
| 1387 | func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1388 | if err != nil { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1389 | if h, ok := t.(tHelper); ok { |
| 1390 | h.Helper() |
| 1391 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1392 | return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) |
| 1393 | } |
| 1394 | |
| 1395 | return true |
| 1396 | } |
| 1397 | |
| 1398 | // Error asserts that a function returned an error (i.e. not `nil`). |
| 1399 | // |
| 1400 | // actualObj, err := SomeFunction() |
| 1401 | // if assert.Error(t, err) { |
| 1402 | // assert.Equal(t, expectedError, err) |
| 1403 | // } |
| 1404 | func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1405 | if err == nil { |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1406 | if h, ok := t.(tHelper); ok { |
| 1407 | h.Helper() |
| 1408 | } |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1409 | return Fail(t, "An error is expected but got nil.", msgAndArgs...) |
| 1410 | } |
| 1411 | |
| 1412 | return true |
| 1413 | } |
| 1414 | |
| 1415 | // EqualError asserts that a function returned an error (i.e. not `nil`) |
| 1416 | // and that it is equal to the provided error. |
| 1417 | // |
| 1418 | // actualObj, err := SomeFunction() |
| 1419 | // assert.EqualError(t, err, expectedErrorString) |
| 1420 | func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { |
| 1421 | if h, ok := t.(tHelper); ok { |
| 1422 | h.Helper() |
| 1423 | } |
| 1424 | if !Error(t, theError, msgAndArgs...) { |
| 1425 | return false |
| 1426 | } |
| 1427 | expected := errString |
| 1428 | actual := theError.Error() |
| 1429 | // don't need to use deep equals here, we know they are both strings |
| 1430 | if expected != actual { |
| 1431 | return Fail(t, fmt.Sprintf("Error message not equal:\n"+ |
| 1432 | "expected: %q\n"+ |
| 1433 | "actual : %q", expected, actual), msgAndArgs...) |
| 1434 | } |
| 1435 | return true |
| 1436 | } |
| 1437 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1438 | // ErrorContains asserts that a function returned an error (i.e. not `nil`) |
| 1439 | // and that the error contains the specified substring. |
| 1440 | // |
| 1441 | // actualObj, err := SomeFunction() |
| 1442 | // assert.ErrorContains(t, err, expectedErrorSubString) |
| 1443 | func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool { |
| 1444 | if h, ok := t.(tHelper); ok { |
| 1445 | h.Helper() |
| 1446 | } |
| 1447 | if !Error(t, theError, msgAndArgs...) { |
| 1448 | return false |
| 1449 | } |
| 1450 | |
| 1451 | actual := theError.Error() |
| 1452 | if !strings.Contains(actual, contains) { |
| 1453 | return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...) |
| 1454 | } |
| 1455 | |
| 1456 | return true |
| 1457 | } |
| 1458 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1459 | // matchRegexp return true if a specified regexp matches a string. |
| 1460 | func matchRegexp(rx interface{}, str interface{}) bool { |
| 1461 | |
| 1462 | var r *regexp.Regexp |
| 1463 | if rr, ok := rx.(*regexp.Regexp); ok { |
| 1464 | r = rr |
| 1465 | } else { |
| 1466 | r = regexp.MustCompile(fmt.Sprint(rx)) |
| 1467 | } |
| 1468 | |
| 1469 | return (r.FindStringIndex(fmt.Sprint(str)) != nil) |
| 1470 | |
| 1471 | } |
| 1472 | |
| 1473 | // Regexp asserts that a specified regexp matches a string. |
| 1474 | // |
| 1475 | // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") |
| 1476 | // assert.Regexp(t, "start...$", "it's not starting") |
| 1477 | func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { |
| 1478 | if h, ok := t.(tHelper); ok { |
| 1479 | h.Helper() |
| 1480 | } |
| 1481 | |
| 1482 | match := matchRegexp(rx, str) |
| 1483 | |
| 1484 | if !match { |
| 1485 | Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) |
| 1486 | } |
| 1487 | |
| 1488 | return match |
| 1489 | } |
| 1490 | |
| 1491 | // NotRegexp asserts that a specified regexp does not match a string. |
| 1492 | // |
| 1493 | // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") |
| 1494 | // assert.NotRegexp(t, "^start", "it's not starting") |
| 1495 | func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { |
| 1496 | if h, ok := t.(tHelper); ok { |
| 1497 | h.Helper() |
| 1498 | } |
| 1499 | match := matchRegexp(rx, str) |
| 1500 | |
| 1501 | if match { |
| 1502 | Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) |
| 1503 | } |
| 1504 | |
| 1505 | return !match |
| 1506 | |
| 1507 | } |
| 1508 | |
| 1509 | // Zero asserts that i is the zero value for its type. |
| 1510 | func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { |
| 1511 | if h, ok := t.(tHelper); ok { |
| 1512 | h.Helper() |
| 1513 | } |
| 1514 | if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { |
| 1515 | return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) |
| 1516 | } |
| 1517 | return true |
| 1518 | } |
| 1519 | |
| 1520 | // NotZero asserts that i is not the zero value for its type. |
| 1521 | func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { |
| 1522 | if h, ok := t.(tHelper); ok { |
| 1523 | h.Helper() |
| 1524 | } |
| 1525 | if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { |
| 1526 | return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) |
| 1527 | } |
| 1528 | return true |
| 1529 | } |
| 1530 | |
| 1531 | // FileExists checks whether a file exists in the given path. It also fails if |
| 1532 | // the path points to a directory or there is an error when trying to check the file. |
| 1533 | func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { |
| 1534 | if h, ok := t.(tHelper); ok { |
| 1535 | h.Helper() |
| 1536 | } |
| 1537 | info, err := os.Lstat(path) |
| 1538 | if err != nil { |
| 1539 | if os.IsNotExist(err) { |
| 1540 | return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) |
| 1541 | } |
| 1542 | return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) |
| 1543 | } |
| 1544 | if info.IsDir() { |
| 1545 | return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...) |
| 1546 | } |
| 1547 | return true |
| 1548 | } |
| 1549 | |
| 1550 | // NoFileExists checks whether a file does not exist in a given path. It fails |
| 1551 | // if the path points to an existing _file_ only. |
| 1552 | func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { |
| 1553 | if h, ok := t.(tHelper); ok { |
| 1554 | h.Helper() |
| 1555 | } |
| 1556 | info, err := os.Lstat(path) |
| 1557 | if err != nil { |
| 1558 | return true |
| 1559 | } |
| 1560 | if info.IsDir() { |
| 1561 | return true |
| 1562 | } |
| 1563 | return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...) |
| 1564 | } |
| 1565 | |
| 1566 | // DirExists checks whether a directory exists in the given path. It also fails |
| 1567 | // if the path is a file rather a directory or there is an error checking whether it exists. |
| 1568 | func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { |
| 1569 | if h, ok := t.(tHelper); ok { |
| 1570 | h.Helper() |
| 1571 | } |
| 1572 | info, err := os.Lstat(path) |
| 1573 | if err != nil { |
| 1574 | if os.IsNotExist(err) { |
| 1575 | return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) |
| 1576 | } |
| 1577 | return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) |
| 1578 | } |
| 1579 | if !info.IsDir() { |
| 1580 | return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...) |
| 1581 | } |
| 1582 | return true |
| 1583 | } |
| 1584 | |
| 1585 | // NoDirExists checks whether a directory does not exist in the given path. |
| 1586 | // It fails if the path points to an existing _directory_ only. |
| 1587 | func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { |
| 1588 | if h, ok := t.(tHelper); ok { |
| 1589 | h.Helper() |
| 1590 | } |
| 1591 | info, err := os.Lstat(path) |
| 1592 | if err != nil { |
| 1593 | if os.IsNotExist(err) { |
| 1594 | return true |
| 1595 | } |
| 1596 | return true |
| 1597 | } |
| 1598 | if !info.IsDir() { |
| 1599 | return true |
| 1600 | } |
| 1601 | return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...) |
| 1602 | } |
| 1603 | |
| 1604 | // JSONEq asserts that two JSON strings are equivalent. |
| 1605 | // |
| 1606 | // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) |
| 1607 | func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { |
| 1608 | if h, ok := t.(tHelper); ok { |
| 1609 | h.Helper() |
| 1610 | } |
| 1611 | var expectedJSONAsInterface, actualJSONAsInterface interface{} |
| 1612 | |
| 1613 | if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { |
| 1614 | return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) |
| 1615 | } |
| 1616 | |
| 1617 | if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { |
| 1618 | return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) |
| 1619 | } |
| 1620 | |
| 1621 | return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) |
| 1622 | } |
| 1623 | |
| 1624 | // YAMLEq asserts that two YAML strings are equivalent. |
| 1625 | func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { |
| 1626 | if h, ok := t.(tHelper); ok { |
| 1627 | h.Helper() |
| 1628 | } |
| 1629 | var expectedYAMLAsInterface, actualYAMLAsInterface interface{} |
| 1630 | |
| 1631 | if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil { |
| 1632 | return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...) |
| 1633 | } |
| 1634 | |
| 1635 | if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil { |
| 1636 | return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...) |
| 1637 | } |
| 1638 | |
| 1639 | return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...) |
| 1640 | } |
| 1641 | |
| 1642 | func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { |
| 1643 | t := reflect.TypeOf(v) |
| 1644 | k := t.Kind() |
| 1645 | |
| 1646 | if k == reflect.Ptr { |
| 1647 | t = t.Elem() |
| 1648 | k = t.Kind() |
| 1649 | } |
| 1650 | return t, k |
| 1651 | } |
| 1652 | |
| 1653 | // diff returns a diff of both values as long as both are of the same type and |
| 1654 | // are a struct, map, slice, array or string. Otherwise it returns an empty string. |
| 1655 | func diff(expected interface{}, actual interface{}) string { |
| 1656 | if expected == nil || actual == nil { |
| 1657 | return "" |
| 1658 | } |
| 1659 | |
| 1660 | et, ek := typeAndKind(expected) |
| 1661 | at, _ := typeAndKind(actual) |
| 1662 | |
| 1663 | if et != at { |
| 1664 | return "" |
| 1665 | } |
| 1666 | |
| 1667 | if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String { |
| 1668 | return "" |
| 1669 | } |
| 1670 | |
| 1671 | var e, a string |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1672 | |
| 1673 | switch et { |
| 1674 | case reflect.TypeOf(""): |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1675 | e = reflect.ValueOf(expected).String() |
| 1676 | a = reflect.ValueOf(actual).String() |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1677 | case reflect.TypeOf(time.Time{}): |
| 1678 | e = spewConfigStringerEnabled.Sdump(expected) |
| 1679 | a = spewConfigStringerEnabled.Sdump(actual) |
| 1680 | default: |
| 1681 | e = spewConfig.Sdump(expected) |
| 1682 | a = spewConfig.Sdump(actual) |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1683 | } |
| 1684 | |
| 1685 | diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ |
| 1686 | A: difflib.SplitLines(e), |
| 1687 | B: difflib.SplitLines(a), |
| 1688 | FromFile: "Expected", |
| 1689 | FromDate: "", |
| 1690 | ToFile: "Actual", |
| 1691 | ToDate: "", |
| 1692 | Context: 1, |
| 1693 | }) |
| 1694 | |
| 1695 | return "\n\nDiff:\n" + diff |
| 1696 | } |
| 1697 | |
| 1698 | func isFunction(arg interface{}) bool { |
| 1699 | if arg == nil { |
| 1700 | return false |
| 1701 | } |
| 1702 | return reflect.TypeOf(arg).Kind() == reflect.Func |
| 1703 | } |
| 1704 | |
| 1705 | var spewConfig = spew.ConfigState{ |
| 1706 | Indent: " ", |
| 1707 | DisablePointerAddresses: true, |
| 1708 | DisableCapacities: true, |
| 1709 | SortKeys: true, |
mpagenko | af80163 | 2020-07-03 10:00:42 +0000 | [diff] [blame] | 1710 | DisableMethods: true, |
khenaidoo | 7d3c558 | 2021-08-11 18:09:44 -0400 | [diff] [blame] | 1711 | MaxDepth: 10, |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1712 | } |
| 1713 | |
Akash Reddy Kankanala | c28f0e2 | 2025-06-16 11:00:55 +0530 | [diff] [blame^] | 1714 | var spewConfigStringerEnabled = spew.ConfigState{ |
| 1715 | Indent: " ", |
| 1716 | DisablePointerAddresses: true, |
| 1717 | DisableCapacities: true, |
| 1718 | SortKeys: true, |
| 1719 | MaxDepth: 10, |
| 1720 | } |
| 1721 | |
Holger Hildebrandt | da7758b | 2020-03-16 11:30:03 +0000 | [diff] [blame] | 1722 | type tHelper interface { |
| 1723 | Helper() |
| 1724 | } |
| 1725 | |
| 1726 | // Eventually asserts that given condition will be met in waitFor time, |
| 1727 | // periodically checking target function each tick. |
| 1728 | // |
| 1729 | // assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) |
| 1730 | func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { |
| 1731 | if h, ok := t.(tHelper); ok { |
| 1732 | h.Helper() |
| 1733 | } |
| 1734 | |
| 1735 | ch := make(chan bool, 1) |
| 1736 | |
| 1737 | timer := time.NewTimer(waitFor) |
| 1738 | defer timer.Stop() |
| 1739 | |
| 1740 | ticker := time.NewTicker(tick) |
| 1741 | defer ticker.Stop() |
| 1742 | |
| 1743 | for tick := ticker.C; ; { |
| 1744 | select { |
| 1745 | case <-timer.C: |
| 1746 | return Fail(t, "Condition never satisfied", msgAndArgs...) |
| 1747 | case <-tick: |
| 1748 | tick = nil |
| 1749 | go func() { ch <- condition() }() |
| 1750 | case v := <-ch: |
| 1751 | if v { |
| 1752 | return true |
| 1753 | } |
| 1754 | tick = ticker.C |
| 1755 | } |
| 1756 | } |
| 1757 | } |
| 1758 | |
| 1759 | // Never asserts that the given condition doesn't satisfy in waitFor time, |
| 1760 | // periodically checking the target function each tick. |
| 1761 | // |
| 1762 | // assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) |
| 1763 | func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { |
| 1764 | if h, ok := t.(tHelper); ok { |
| 1765 | h.Helper() |
| 1766 | } |
| 1767 | |
| 1768 | ch := make(chan bool, 1) |
| 1769 | |
| 1770 | timer := time.NewTimer(waitFor) |
| 1771 | defer timer.Stop() |
| 1772 | |
| 1773 | ticker := time.NewTicker(tick) |
| 1774 | defer ticker.Stop() |
| 1775 | |
| 1776 | for tick := ticker.C; ; { |
| 1777 | select { |
| 1778 | case <-timer.C: |
| 1779 | return true |
| 1780 | case <-tick: |
| 1781 | tick = nil |
| 1782 | go func() { ch <- condition() }() |
| 1783 | case v := <-ch: |
| 1784 | if v { |
| 1785 | return Fail(t, "Condition satisfied", msgAndArgs...) |
| 1786 | } |
| 1787 | tick = ticker.C |
| 1788 | } |
| 1789 | } |
| 1790 | } |
khenaidoo | 7d3c558 | 2021-08-11 18:09:44 -0400 | [diff] [blame] | 1791 | |
| 1792 | // ErrorIs asserts that at least one of the errors in err's chain matches target. |
| 1793 | // This is a wrapper for errors.Is. |
| 1794 | func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool { |
| 1795 | if h, ok := t.(tHelper); ok { |
| 1796 | h.Helper() |
| 1797 | } |
| 1798 | if errors.Is(err, target) { |
| 1799 | return true |
| 1800 | } |
| 1801 | |
| 1802 | var expectedText string |
| 1803 | if target != nil { |
| 1804 | expectedText = target.Error() |
| 1805 | } |
| 1806 | |
| 1807 | chain := buildErrorChainString(err) |
| 1808 | |
| 1809 | return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+ |
| 1810 | "expected: %q\n"+ |
| 1811 | "in chain: %s", expectedText, chain, |
| 1812 | ), msgAndArgs...) |
| 1813 | } |
| 1814 | |
| 1815 | // NotErrorIs asserts that at none of the errors in err's chain matches target. |
| 1816 | // This is a wrapper for errors.Is. |
| 1817 | func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool { |
| 1818 | if h, ok := t.(tHelper); ok { |
| 1819 | h.Helper() |
| 1820 | } |
| 1821 | if !errors.Is(err, target) { |
| 1822 | return true |
| 1823 | } |
| 1824 | |
| 1825 | var expectedText string |
| 1826 | if target != nil { |
| 1827 | expectedText = target.Error() |
| 1828 | } |
| 1829 | |
| 1830 | chain := buildErrorChainString(err) |
| 1831 | |
| 1832 | return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+ |
| 1833 | "found: %q\n"+ |
| 1834 | "in chain: %s", expectedText, chain, |
| 1835 | ), msgAndArgs...) |
| 1836 | } |
| 1837 | |
| 1838 | // ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. |
| 1839 | // This is a wrapper for errors.As. |
| 1840 | func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool { |
| 1841 | if h, ok := t.(tHelper); ok { |
| 1842 | h.Helper() |
| 1843 | } |
| 1844 | if errors.As(err, target) { |
| 1845 | return true |
| 1846 | } |
| 1847 | |
| 1848 | chain := buildErrorChainString(err) |
| 1849 | |
| 1850 | return Fail(t, fmt.Sprintf("Should be in error chain:\n"+ |
| 1851 | "expected: %q\n"+ |
| 1852 | "in chain: %s", target, chain, |
| 1853 | ), msgAndArgs...) |
| 1854 | } |
| 1855 | |
| 1856 | func buildErrorChainString(err error) string { |
| 1857 | if err == nil { |
| 1858 | return "" |
| 1859 | } |
| 1860 | |
| 1861 | e := errors.Unwrap(err) |
| 1862 | chain := fmt.Sprintf("%q", err.Error()) |
| 1863 | for e != nil { |
| 1864 | chain += fmt.Sprintf("\n\t%q", e.Error()) |
| 1865 | e = errors.Unwrap(e) |
| 1866 | } |
| 1867 | return chain |
| 1868 | } |